Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
36.22% covered (danger)
36.22%
925 / 2554
10.20% covered (danger)
10.20%
5 / 49
CRAP
0.00% covered (danger)
0.00%
0 / 1
AppController
36.14% covered (danger)
36.14%
922 / 2551
10.20% covered (danger)
10.20%
5 / 49
199327.23
0.00% covered (danger)
0.00%
0 / 1
 processSGF
98.11% covered (success)
98.11%
52 / 53
0.00% covered (danger)
0.00%
0 / 1
15
 xFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 yFlip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getInitialPositionEnd
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 getInitialPosition
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
6
 getInvisibleSets
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getDeletedSets
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 startPageUpdate
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
5.03
 uotd
0.00% covered (danger)
0.00%
0 / 157
0.00% covered (danger)
0.00%
0 / 1
2070
 deleteUnusedStatuses
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
72
 saveSolvedNumber
78.12% covered (warning)
78.12%
25 / 32
0.00% covered (danger)
0.00%
0 / 1
13.51
 resetUserElos
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 handleContribution
52.94% covered (warning)
52.94%
9 / 17
0.00% covered (danger)
0.00%
0 / 1
2.42
 getAllTags
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 getNewTsumego
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 publishSingle
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
30
 getTsumegoOfTheDay
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 1
1190
 ratingMatch
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
992
 rating2
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
132
 encrypt
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 decrypt
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 checkPictureLarge
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 checkPicture
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 getTsumegoRankx
0.00% covered (danger)
0.00%
0 / 42
0.00% covered (danger)
0.00%
0 / 1
506
 adjustElo
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
132
 getTsumegoElo
60.38% covered (warning)
60.38%
32 / 53
0.00% covered (danger)
0.00%
0 / 1
95.70
 getTsumegoRankVal
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 getTsumegoRankMax
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
506
 saveDanSolveCondition
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 updateSprintCondition
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
4.00
 updateGoldenCondition
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 setPotionCondition
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
 updateGems
3.85% covered (danger)
3.85%
4 / 104
0.00% covered (danger)
0.00%
0 / 1
2183.48
 checkProblemNumberAchievements
42.39% covered (danger)
42.39%
39 / 92
0.00% covered (danger)
0.00%
0 / 1
166.38
 checkDanSolveAchievements
46.82% covered (danger)
46.82%
81 / 173
0.00% covered (danger)
0.00%
0 / 1
545.62
 checkForLocked
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 checkNoErrorAchievements
50.77% covered (warning)
50.77%
33 / 65
0.00% covered (danger)
0.00%
0 / 1
51.48
 checkTimeModeAchievements
35.40% covered (danger)
35.40%
40 / 113
0.00% covered (danger)
0.00%
0 / 1
2273.83
 checkRatingAchievements
54.44% covered (warning)
54.44%
49 / 90
0.00% covered (danger)
0.00%
0 / 1
95.92
 checkLevelAchievements
72.22% covered (warning)
72.22%
65 / 90
0.00% covered (danger)
0.00%
0 / 1
42.63
 checkSetCompletedAchievements
19.72% covered (danger)
19.72%
14 / 71
0.00% covered (danger)
0.00%
0 / 1
166.54
 setAchievementSpecial
0.00% covered (danger)
0.00%
0 / 184
0.00% covered (danger)
0.00%
0 / 1
4160
 checkSetAchievements
18.10% covered (danger)
18.10%
40 / 221
0.00% covered (danger)
0.00%
0 / 1
2533.09
 getXPJump
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
72
 updateXP
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
3.58
 getPartitionRange
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
56
 handleSearchSettings
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 signIn
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
2.02
 beforeFilter
83.23% covered (warning)
83.23%
278 / 334
0.00% covered (danger)
0.00%
0 / 1
94.76
 afterFilter
n/a
0 / 0
n/a
0 / 0
1
1<?php
2
3App::uses('Auth', 'Utility');
4App::uses('TsumegoFilters', 'Utility');
5App::uses('TimeMode', 'Utility');
6
7class AppController extends Controller {
8    public $viewClass = 'App';
9
10    public $components = [
11        'Session',
12        //'DebugKit.Toolbar',
13        'Flash',
14        'PlayResultProcessor'
15    ];
16
17    public static function processSGF($sgf) {
18        $aw = strpos($sgf, 'AW');
19        $ab = strpos($sgf, 'AB');
20        $boardSizePos = strpos($sgf, 'SZ');
21        $boardSize = 19;
22        $sgfArr = str_split($sgf);
23        if ($boardSizePos !== false) {
24            $boardSize = $sgfArr[$boardSizePos + 3] . '' . $sgfArr[$boardSizePos + 4];
25        }
26        if (substr($boardSize, 1) == ']') {
27            $boardSize = substr($boardSize, 0, 1);
28        }
29
30        $black = AppController::getInitialPosition($ab, $sgfArr, 'x');
31        $white = AppController::getInitialPosition($aw, $sgfArr, 'o');
32        $stones = array_merge($black, $white);
33
34        $board = [];
35        for ($i = 0; $i < 19; $i++) {
36            $board[$i] = [];
37            for ($j = 0; $j < 19; $j++) {
38                $board[$i][$j] = '-';
39            }
40        }
41        $lowestX = 18;
42        $lowestY = 18;
43        $highestX = 0;
44        $highestY = 0;
45        $stonesCount = count($stones);
46        for ($i = 0; $i < $stonesCount; $i++) {
47            if ($stones[$i][0] < $lowestX) {
48                $lowestX = $stones[$i][0];
49            }
50            if ($stones[$i][0] > $highestX) {
51                $highestX = $stones[$i][0];
52            }
53            if ($stones[$i][1] < $lowestY) {
54                $lowestY = $stones[$i][1];
55            }
56            if ($stones[$i][1] > $highestY) {
57                $highestY = $stones[$i][1];
58            }
59        }
60        if (18 - $lowestX < $lowestX) {
61            $stones = AppController::xFlip($stones);
62        }
63        if (18 - $lowestY < $lowestY) {
64            $stones = AppController::yFlip($stones);
65        }
66        $highestX = 0;
67        $highestY = 0;
68        $stonesCount = count($stones);
69        for ($i = 0; $i < $stonesCount; $i++) {
70            if ($stones[$i][0] > $highestX) {
71                $highestX = $stones[$i][0];
72            }
73            if ($stones[$i][1] > $highestY) {
74                $highestY = $stones[$i][1];
75            }
76            $board[$stones[$i][0]][$stones[$i][1]] = $stones[$i][2];
77        }
78        $tInfo = [];
79        $tInfo[0] = $highestX;
80        $tInfo[1] = $highestY;
81        $arr = [];
82        $arr[0] = $board;
83        $arr[1] = $stones;
84        $arr[2] = $tInfo;
85        $arr[3] = $boardSize;
86
87        return $arr;
88    }
89
90    public static function xFlip($stones) {
91        $stonesCount = count($stones);
92        for ($i = 0; $i < $stonesCount; $i++) {
93            $stones[$i][0] = 18 - $stones[$i][0];
94        }
95
96        return $stones;
97    }
98
99    public static function yFlip($stones) {
100        $stonesCount = count($stones);
101        for ($i = 0; $i < $stonesCount; $i++) {
102            $stones[$i][1] = 18 - $stones[$i][1];
103        }
104
105        return $stones;
106    }
107
108    public static function getInitialPositionEnd($pos, $sgfArr) {
109        $endCondition = 0;
110        $currentPos1 = $pos + 2;
111        $currentPos2 = $pos + 5;
112        while ($sgfArr[$currentPos1] == '[' && $sgfArr[$currentPos2] == ']') {
113            $endCondition = $currentPos2;
114            $currentPos1 += 4;
115            $currentPos2 += 4;
116        }
117
118        return $endCondition;
119    }
120
121    public static function getInitialPosition($pos, $sgfArr, $color) {
122        $arr = [];
123        $end = AppController::getInitialPositionEnd($pos, $sgfArr);
124        for ($i = $pos + 2; $i < $end; $i++) {
125            if ($sgfArr[$i] != '[' && $sgfArr[$i] != ']') {
126                array_push($arr, strtolower($sgfArr[$i]));
127            }
128        }
129        $alphabet = array_flip(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']);
130        $xy = true;
131        $arr2 = [];
132        $c = 0;
133        $arrCount = count($arr);
134        for ($i = 0; $i < $arrCount; $i++) {
135            $arr[$i] = $alphabet[$arr[$i]];
136            if ($xy) {
137                $arr2[$c] = [];
138                $arr2[$c][0] = $arr[$i];
139            } else {
140                $arr2[$c][1] = $arr[$i];
141                $arr2[$c][2] = $color;
142                $c++;
143            }
144            $xy = !$xy;
145        }
146
147        return $arr2;
148    }
149
150    protected function getInvisibleSets() {
151        $this->loadModel('Set');
152        $invisibleSets = [];
153        $in = $this->Set->find('all', ['conditions' => ['public' => 0]]);
154        if (!$in) {
155            $in = [];
156        }
157        foreach ($in as $item) {
158            $invisibleSets[] = $item['Set']['id'];
159        }
160
161        return $invisibleSets;
162    }
163
164    protected function getDeletedSets() {
165        $dSets = [];
166        $de = $this->Set->find('all', ['conditions' => ['public' => -1]]);
167        if (!$de) {
168            $de = [];
169        }
170        foreach ($de as $item) {
171            $dSets[] = $item['Set']['id'];
172        }
173
174        return $dSets;
175    }
176
177    /**
178     * @return void
179     */
180    public static function startPageUpdate() {
181        $str = '';
182        $latest = ClassRegistry::init('AchievementStatus')->find('all', ['limit' => 7, 'order' => 'created DESC']);
183        if (!$latest) {
184            $latest = [];
185        }
186        $latestCount = count($latest);
187        for ($i = 0; $i < $latestCount; $i++) {
188            $a = ClassRegistry::init('Achievement')->findById($latest[$i]['AchievementStatus']['achievement_id']);
189            $u = ClassRegistry::init('User')->findById($latest[$i]['AchievementStatus']['user_id']);
190            if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
191                $startPageUser = AppController::checkPicture($u);
192            } else {
193                $startPageUser = $u['User']['name'];
194            }
195            $latest[$i]['AchievementStatus']['name'] = $a['Achievement']['name'];
196            $latest[$i]['AchievementStatus']['color'] = $a['Achievement']['color'];
197            $latest[$i]['AchievementStatus']['image'] = $a['Achievement']['image'];
198            $latest[$i]['AchievementStatus']['user'] = $startPageUser;
199            $str .= '<div class="quote1"><div class="quote1a"><a href="/achievements/view/' . $a['Achievement']['id'] . '"><img src="/img/' . $a['Achievement']['image'] . '.png" width="34px"></a></div>';
200            $str .= '<div class="quote1b">Achievement gained by ' . $startPageUser . ':<br><div class=""><b>' . $a['Achievement']['name'] . '</b></div></div></div>';
201        }
202        file_put_contents('mainPageAjax.txt', $str);
203    }
204
205    /**
206     * @return void
207     */
208    protected function uotd() { //routine1
209        $this->loadModel('User');
210        $this->loadModel('DayRecord');
211        $this->loadModel('TsumegoAttempt');
212        $this->loadModel('Achievement');
213        $this->loadModel('AchievementCondition');
214        $today = date('Y-m-d');
215        $ux2 = $this->User->find('all', [
216            'limit' => '8',
217            'order' => 'reuse3 DESC',
218            'conditions' => [
219                'NOT' => ['id' => [33]],
220            ],
221        ]);
222        if (!$ux2) {
223            $ux2 = [];
224        }
225        $last = $this->DayRecord->find('all', ['limit' => '7', 'order' => 'date DESC']);
226        if (!$last) {
227            $last = [];
228        }
229        $lastUotds = [];
230        $lastUsers = [];
231        foreach ($last as $item) {
232            $lastUotds[] = $item['DayRecord']['user_id'];
233        }
234        foreach ($ux2 as $item) {
235            $lastUsers[] = $item['User']['id'];
236        }
237        $resultUser = 72;
238        $lastUsersCount = count($lastUsers);
239        for ($i = 0; $i < $lastUsersCount; $i++) {
240            $foundUser = false;
241            $lastUotdsCount = count($lastUotds);
242            for ($j = 0; $j < $lastUotdsCount; $j++) {
243                if ($lastUsers[$i] == $lastUotds[$j]) {
244                    $foundUser = true;
245                }
246            }
247            if (!$foundUser) {
248                $resultUser = $lastUsers[$i];
249
250                break;
251            }
252        }
253        $ux = $this->User->findById($resultUser);
254
255        $recentlyUsed = [];
256        $d = 1;
257        while ($d <= 10) {
258            $ru = $this->DayRecord->find('first', ['conditions' => ['date' => date('Y-m-d', strtotime('-' . $d . ' days'))]]);
259            if ($ru) {
260                array_push($recentlyUsed, $ru);
261            }
262            $d++;
263        }
264        $currentQuote = 'q01';
265        $newQuote = 'q01';
266        $quoteChosen = false;
267        while (!$quoteChosen) {
268            $newQuote = rand(1, 45);
269            if ($newQuote < 10) {
270                $newQuote = 'q0' . $newQuote;
271            } else {
272                $newQuote = 'q' . $newQuote;
273            }
274
275            $f = false;
276            $recentlyUsedCount = count($recentlyUsed);
277            for ($i = 0; $i < $recentlyUsedCount; $i++) {
278                if ($newQuote == $recentlyUsed[$i]['DayRecord']['quote']) {
279                    $f = true;
280                }
281            }
282            if (!$f) {
283                $quoteChosen = true;
284            }
285        }
286        $currentQuote = $newQuote;
287        $dayUserRand = 1;
288        $uotdChosen = false;
289        while (!$uotdChosen) {
290            $dayUserRand = rand(1, 39);
291            $f = false;
292            $recentlyUsedCount = count($recentlyUsed);
293            for ($i = 0; $i < $recentlyUsedCount; $i++) {
294                if ($dayUserRand == $recentlyUsed[$i]['DayRecord']['userbg']) {
295                    $f = true;
296                }
297            }
298            if (!$f) {
299                $uotdChosen = true;
300            }
301        }
302        $activity = $this->TsumegoAttempt->find('all', ['limit' => 40000, 'conditions' => ['DATE(TsumegoAttempt.updated)' => date('Y-m-d', strtotime('yesterday'))]]);
303        if (!$activity) {
304            $activity = [];
305        }
306        $visitedProblems = count($activity);
307
308        //how many users today
309        $usersNum = [];
310        $activity = $this->User->find('all', ['limit' => 400, 'order' => 'created DESC']);
311        if (!$activity) {
312            $activity = [];
313        }
314        $activityCount = count($activity);
315        for ($i = 0; $i < $activityCount; $i++) {
316            $a = new DateTime($activity[$i]['User']['created']);
317            if ($a->format('Y-m-d') == $today) {
318                array_push($usersNum, $activity[$i]['User']);
319            }
320        }
321        $gemRand1 = rand(0, 2);
322        $gemRand2 = rand(0, 2);
323        $gemRand3 = rand(0, 2);
324
325        $arch1 = ClassRegistry::init('Achievement')->findById(111);
326        if ($gemRand1 == 0) {
327            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on an easy ddk problem.';
328        } elseif ($gemRand1 == 1) {
329            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a regular ddk problem.';
330        } elseif ($gemRand1 == 2) {
331            $arch1['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult ddk problem.';
332        }
333        ClassRegistry::init('Achievement')->save($arch1);
334        $arch2 = ClassRegistry::init('Achievement')->findById(112);
335        if ($gemRand2 == 0) {
336            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on an easy sdk problem.';
337        } elseif ($gemRand2 == 1) {
338            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a regular sdk problem.';
339        } elseif ($gemRand2 == 2) {
340            $arch2['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult sdk problem.';
341        }
342        ClassRegistry::init('Achievement')->save($arch2);
343        $arch3 = ClassRegistry::init('Achievement')->findById(113);
344        if ($gemRand3 == 0) {
345            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on an easy dan problem.';
346        } elseif ($gemRand3 == 1) {
347            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a regular dan problem.';
348        } elseif ($gemRand3 == 2) {
349            $arch3['Achievement']['description'] = 'Has a chance to trigger once a day on a difficult dan problem.';
350        }
351        ClassRegistry::init('Achievement')->save($arch3);
352
353        $this->DayRecord->create();
354        $dateUser = [];
355        $dateUser['DayRecord']['user_id'] = $ux['User']['id'];
356        $dateUser['DayRecord']['date'] = $today;
357        $dateUser['DayRecord']['solved'] = $ux['User']['reuse3'];
358        $dateUser['DayRecord']['quote'] = $currentQuote;
359        $dateUser['DayRecord']['userbg'] = $dayUserRand;
360        $dateUser['DayRecord']['tsumego'] = $this->getTsumegoOfTheDay();
361        $dateUser['DayRecord']['newTsumego'] = $this->getNewTsumego();
362        $dateUser['DayRecord']['usercount'] = count($usersNum);
363        $dateUser['DayRecord']['visitedproblems'] = $visitedProblems;
364        $dateUser['DayRecord']['gems'] = $gemRand1 . '-' . $gemRand2 . '-' . $gemRand3;
365        $dateUser['DayRecord']['gemCounter1'] = 0;
366        $dateUser['DayRecord']['gemCounter2'] = 0;
367        $dateUser['DayRecord']['gemCounter3'] = 0;
368        $this->DayRecord->save($dateUser);
369
370        ClassRegistry::init('AchievementCondition')->create();
371        $achievementCondition = [];
372        $achievementCondition['AchievementCondition']['user_id'] = $ux['User']['id'];
373        $achievementCondition['AchievementCondition']['set_id'] = 0;
374        $achievementCondition['AchievementCondition']['category'] = 'uotd';
375        $achievementCondition['AchievementCondition']['value'] = 1;
376        ClassRegistry::init('AchievementCondition')->save($achievementCondition);
377
378        //delete duplicated DayRecords
379        $dr = $this->DayRecord->find('all');
380        if (!$dr) {
381            $dr = [];
382        }
383        $duplicates = [];
384        $drCount = count($dr);
385        for ($i = 0; $i < $drCount; $i++) {
386            $alreadyFound = [];
387            for ($j = 0; $j < $drCount; $j++) {
388                if ($i != $j && $dr[$j]['DayRecord']['date'] == $dr[$i]['DayRecord']['date']) {
389                    $found = false;
390                    $alreadyFoundCount = count($alreadyFound);
391                    for ($k = 0; $k < $alreadyFoundCount; $k++) {
392                        if ($alreadyFound[$k]['DayRecord']['id'] == $dr[$i]['DayRecord']['id'] || $alreadyFound[$k]['DayRecord']['id'] == $dr[$j]['DayRecord']['id']) {
393                            $found = true;
394                        }
395                    }
396                    if (!$found) {
397                        array_push($duplicates, $dr[$i]['DayRecord']['date']);
398                        array_push($alreadyFound, $dr[$i]);
399                    }
400                }
401            }
402        }
403        $duplicates = array_count_values($duplicates);
404        foreach ($duplicates as $key => $value) {
405            while ($duplicates[$key] > 1) {
406                $drd = $this->DayRecord->find('first', ['conditions' => ['date' => $key]]);
407                if ($drd) {
408                    $this->DayRecord->delete($drd['DayRecord']['id']);
409                }
410                $duplicates[$key]--;
411            }
412        }
413    }
414
415    public static function deleteUnusedStatuses(int $uid): void {
416        $s = ClassRegistry::init('Set')->find('all', [
417            'conditions' => [
418                'OR' => [
419                    ['public' => 1],
420                    ['public' => 0],
421                ],
422            ],
423        ]) ?: [];
424        $ids = [];
425        $sCount = count($s);
426        for ($i = 0; $i < $sCount; $i++) {
427            $tSet = TsumegoUtil::collectTsumegosFromSet($s[$i]['Set']['id']);
428            foreach ($tSet as $item) {
429                $ids[] = $item['Tsumego']['id'];
430            }
431        }
432        $ut = ClassRegistry::init('TsumegoStatus')->find('all', [
433            'conditions' => [
434                'user_id' => $uid,
435                'NOT' => [
436                    'tsumego_id' => $ids,
437                ],
438            ],
439        ]);
440        if (!$ut) {
441            $ut = [];
442        }
443        $utCount = count($ut);
444        for ($i = 0; $i < $utCount; $i++) {
445            $test1 = ClassRegistry::init('Tsumego')->findById($ut[$i]['TsumegoStatus']['tsumego_id']);
446            $test2 = ClassRegistry::init('SetConnection')->find('first', ['conditions' => ['tsumego_id' => $test1['Tsumego']['id']]]);
447            if (!$test2) {
448                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
449
450                continue;
451            }
452            $test3 = ClassRegistry::init('Set')->find('first', [
453                'id' => $test2['SetConnection']['set_id'],
454                'OR' => [
455                    ['public' => 1],
456                    ['public' => 0],
457                ],
458            ]);
459            if ($test3 == null) {
460                ClassRegistry::init('TsumegoStatus')->delete($ut[$i]['TsumegoStatus']['id']);
461            }
462        }
463    }
464
465    protected function saveSolvedNumber($uid) {
466        $this->loadModel('User');
467        $this->loadModel('TsumegoStatus');
468        $this->loadModel('Set');
469        $this->loadModel('SetConnection');
470
471        $solvedUts2 = 0;
472        $tsumegos = $this->SetConnection->find('all');
473        if (!$tsumegos) {
474            $tsumegos = [];
475        }
476        $uts = $this->TsumegoStatus->find('all', ['order' => 'updated DESC', 'conditions' => ['user_id' => $uid]]);
477        if (!$uts) {
478            $uts = [];
479        }
480        $setKeys = [];
481        $setArray = $this->Set->find('all', ['conditions' => ['public' => 1]]);
482        if (!$setArray) {
483            $setArray = [];
484        }
485
486        $setArrayCount = count($setArray);
487        for ($i = 0; $i < $setArrayCount; $i++) {
488            $setKeys[$setArray[$i]['Set']['id']] = $setArray[$i]['Set']['id'];
489        }
490
491        $scs = [];
492        $tsumegosCount = count($tsumegos);
493        for ($j = 0; $j < $tsumegosCount; $j++) {
494            if (!isset($scs[$tsumegos[$j]['SetConnection']['tsumego_id']])) {
495                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']] = 1;
496            } else {
497                $scs[$tsumegos[$j]['SetConnection']['tsumego_id']]++;
498            }
499        }
500        $utsCount = count($uts);
501        for ($j = 0; $j < $utsCount; $j++) {
502            if ($uts[$j]['TsumegoStatus']['status'] == 'S' || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C') {
503                if (isset($scs[$uts[$j]['TsumegoStatus']['tsumego_id']])) {
504                    $solvedUts2 += $scs[$uts[$j]['TsumegoStatus']['tsumego_id']];
505                }
506            }
507        }
508        Auth::getUser()['solved'] = $solvedUts2;
509        Auth::saveUser();
510
511        return $solvedUts2;
512    }
513
514    /**
515     * @return void
516     */
517    protected function resetUserElos() {
518        $this->loadModel('User');
519
520        $u = $this->User->find('all', [
521            'conditions' => [
522                'id >=' => 15000,
523                'id <=' => 19000,
524            ],
525        ]);
526        if (!$u) {
527            $u = [];
528        }
529
530        $uCount = count($u);
531        for ($i = 0; $i < $uCount; $i++) {
532            $u[$i]['User']['rating'] = 900;
533            $u[$i]['User']['solved2'] = 0;
534            $this->User->save($u[$i]);
535        }
536    }
537
538    /**
539     * @param int $uid User ID
540     * @param string $action Action type
541     *
542     * @return void
543     */
544    public static function handleContribution($uid, $action) {
545        $uc = ClassRegistry::init('UserContribution')->find('first', ['conditions' => ['user_id' => $uid]]);
546        if ($uc == null) {
547            $uc = [];
548            $uc['UserContribution']['user_id'] = $uid;
549            $uc['UserContribution']['added_tag'] = 0;
550            $uc['UserContribution']['created_tag'] = 0;
551            $uc['UserContribution']['made_proposal'] = 0;
552            $uc['UserContribution']['reviewed'] = 0;
553            $uc['UserContribution']['score'] = 0;
554            ClassRegistry::init('UserContribution')->create();
555        }
556        $uc['UserContribution'][$action] += 1;
557        $uc['UserContribution']['score']
558        = $uc['UserContribution']['added_tag']
559        + $uc['UserContribution']['created_tag'] * 3
560        + $uc['UserContribution']['made_proposal'] * 5
561        + $uc['UserContribution']['reviewed'] * 2;
562        ClassRegistry::init('UserContribution')->save($uc);
563    }
564
565    public static function getAllTags($not) {
566        $a = [];
567        $notApproved = ClassRegistry::init('TagName')->find('all', ['conditions' => ['approved' => 0]]);
568        if (!$notApproved) {
569            $notApproved = [];
570        }
571        $notCount = count($not);
572        for ($i = 0; $i < $notCount; $i++) {
573            array_push($a, $not[$i]['Tag']['tag_name_id']);
574        }
575        $notApprovedCount = count($notApproved);
576        for ($i = 0; $i < $notApprovedCount; $i++) {
577            array_push($a, $notApproved[$i]['TagName']['id']);
578        }
579        $tn = ClassRegistry::init('TagName')->find('all', [
580            'conditions' => [
581                'NOT' => ['id' => $a],
582            ],
583        ]);
584        if (!$tn) {
585            $tn = [];
586        }
587        $sorted = [];
588        $keys = [];
589        $tnCount = count($tn);
590        for ($i = 0; $i < $tnCount; $i++) {
591            array_push($sorted, $tn[$i]['TagName']['name']);
592            $keys[$tn[$i]['TagName']['name']] = $tn[$i];
593        }
594        sort($sorted);
595        $s2 = [];
596        $sortedCount = count($sorted);
597        for ($i = 0; $i < $sortedCount; $i++) {
598            array_push($s2, $keys[$sorted[$i]]);
599        }
600
601        return $s2;
602    }
603
604    protected function getNewTsumego() {
605        $this->loadModel('Schedule');
606        $date = date('Y-m-d', strtotime('today'));
607        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
608        if (!$s) {
609            $s = [];
610        }
611        $id = 0;
612        $sCount = count($s);
613        for ($i = 0; $i < $sCount; $i++) {
614            $id = $this->publishSingle($s[$i]['Schedule']['tsumego_id'], $s[$i]['Schedule']['set_id'], $s[$i]['Schedule']['date']);
615            $s[$i]['Schedule']['tsumego_id'] = $id;
616            $s[$i]['Schedule']['published'] = 1;
617            $this->Schedule->save($s[$i]);
618        }
619
620        return $id;
621    }
622
623    protected function publishSingle($t = null, $to = null, $date = null) {
624        $this->loadModel('Tsumego');
625        $this->loadModel('Sgf');
626        $this->loadModel('SetConnection');
627        $this->loadModel('PublishDate');
628        $ts = $this->Tsumego->findById($t);
629
630        $id = $this->Tsumego->find('first', ['limit' => 1, 'order' => 'id DESC']);
631        if (!$id) {
632            return null;
633        }
634        $id = $id['Tsumego']['id'];
635        $id += 1;
636
637        $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $ts['Tsumego']['id']]]);
638        if ($scT != null) {
639            $scT['SetConnection']['set_id'] = $to;
640            $scT['SetConnection']['tsumego_id'] = $id;
641            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
642            $this->SetConnection->save($scT);
643        } else {
644            $scT = [];
645            $scT['SetConnection']['set_id'] = $to;
646            $scT['SetConnection']['tsumego_id'] = $id;
647            $scT['SetConnection']['num'] = $ts['Tsumego']['num'];
648            $this->SetConnection->create();
649            $this->SetConnection->save($scT);
650        }
651
652        $sid = $ts['Tsumego']['id'];
653        $ts['Tsumego']['id'] = $id;
654        $ts['Tsumego']['created'] = $date . ' 22:00:00';
655        $ts['Tsumego']['solved'] = 0;
656        $ts['Tsumego']['failed'] = 0;
657        $ts['Tsumego']['userWin'] = 0;
658        $ts['Tsumego']['userLoss'] = 0;
659        $this->Tsumego->create();
660        $this->Tsumego->save($ts);
661        $this->Tsumego->delete($sid);
662
663        $sgfs = $this->Sgf->find('all', ['conditions' => ['tsumego_id' => $t]]);
664        if (!$sgfs) {
665            $sgfs = [];
666        }
667        $sgfsCount = count($sgfs);
668        for ($i = 0; $i < $sgfsCount; $i++) {
669            $sgfs[$i]['Sgf']['tsumego_id'] = $id;
670            $this->Sgf->save($sgfs[$i]);
671        }
672        $x = [];
673        $x['PublishDate']['date'] = $date . ' 22:00:00';
674        $x['PublishDate']['tsumego_id'] = $id;
675        $this->PublishDate->create();
676        $this->PublishDate->save($x);
677
678        return $id;
679    }
680
681    protected function getTsumegoOfTheDay() {
682        $this->loadModel('TsumegoAttempt');
683        $this->loadModel('TsumegoRatingAttempt');
684        $this->loadModel('Schedule');
685        $this->loadModel('Tsumego');
686        $this->loadModel('SetConnection');
687
688        $ut = $this->TsumegoRatingAttempt->find('all', ['limit' => 10000, 'order' => 'created DESC', 'conditions' => ['status' => 'S']]);
689        if (!$ut) {
690            $ut = [];
691        }
692        $out = $this->TsumegoAttempt->find('all', ['limit' => 30000, 'order' => 'updated DESC', 'conditions' => ['gain >=' => 40]]);
693        if (!$out) {
694            $out = [];
695        }
696
697        $date = date('Y-m-d', strtotime('yesterday'));
698        $s = $this->Schedule->find('all', ['conditions' => ['date' => $date]]);
699        if (!$s) {
700            $s = [];
701        }
702        $ids = [];
703        $utCount = count($ut);
704        for ($i = 0; $i < $utCount; $i++) {
705            $date2 = new DateTime($ut[$i]['TsumegoRatingAttempt']['created']);
706            $date2 = $date2->format('Y-m-d');
707            if ($date === $date2) {
708                array_push($ids, $ut[$i]['TsumegoRatingAttempt']['tsumego_id']);
709            }
710        }
711        $ids = array_count_values($ids);
712        $highest = 0;
713        $best = [];
714        foreach ($ids as $key => $value) {
715            if ($value > $highest) {
716                $highest = $value;
717            }
718        }
719        foreach ($ids as $key => $value) {
720            if ($value == $highest) {
721                $x = [];
722                $x[$key] = $value;
723                array_push($best, $x);
724            }
725        }
726        $ids2 = [];
727        $out2 = [];
728        $outCount = count($out);
729        for ($i = 0; $i < $outCount; $i++) {
730            $date2 = new DateTime($out[$i]['TsumegoAttempt']['updated']);
731            $date2 = $date2->format('Y-m-d');
732            if ($date === $date2) {
733                array_push($ids2, $out[$i]['TsumegoAttempt']['tsumego_id']);
734                array_push($out2, $out[$i]);
735            }
736        }
737        $ids2 = array_count_values($ids2);
738        $highest = 0;
739        $best2 = [];
740        foreach ($ids2 as $key => $value) {
741            if ($value > $highest) {
742                $highest = $value;
743            }
744        }
745        $done = false;
746        $found = 0;
747        $decrement = 0;
748        $best3 = [];
749        $findNum = 20;
750        while (!$done) {
751            foreach ($ids2 as $key => $value) {
752                if ($value == $highest - $decrement) {
753                    array_push($best2, $key);
754                    array_push($best3, $value);
755                    $found++;
756                }
757            }
758            $decrement++;
759            if ($found < $findNum) {
760                $done = false;
761            } else {
762                $done = true;
763            }
764        }
765        $newBest = [];
766        for ($j = 0; $j < $findNum; $j++) {
767            $newBest[$j] = [];
768        }
769        $out2Count = count($out2);
770        for ($i = 0; $i < $out2Count; $i++) {
771            for ($j = 0; $j < $findNum; $j++) {
772                if ($out2[$i]['TsumegoAttempt']['tsumego_id'] == $best2[$j]) {
773                    $x = [];
774                    $x['tid'] = $out2[$i]['TsumegoAttempt']['tsumego_id'];
775                    $tx = $this->Tsumego->findById($x['tid']);
776                    $scT = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $tx['Tsumego']['id']]]);
777                    $tx['Tsumego']['set_id'] = $scT['SetConnection']['set_id'];
778                    $x['sid'] = $tx['Tsumego']['set_id'];
779                    $x['status'] = $out2[$i]['TsumegoAttempt']['solved'];
780                    $x['seconds'] = $out2[$i]['TsumegoAttempt']['seconds'];
781
782                    $newBest[$j][] = $x;
783                }
784            }
785        }
786        $newBestCount = count($newBest);
787        for ($i = 0; $i < $newBestCount; $i++) {
788            $sum = 0;
789            $newBestICount = count($newBest[$i]);
790            for ($j = 0; $j < $newBestICount; $j++) {
791                if ($newBest[$i][$j]['seconds'] != null) {
792                    if ($newBest[$i][$j]['seconds'] > 300) {
793                        $newBest[$i][$j]['seconds'] = 300;
794                    }
795                    $sum += $newBest[$i][$j]['seconds'];
796                }
797            }
798            $sum = $sum * count($newBest[$i]);
799            $newBest[$i]['sum'] = $sum;
800        }
801        $highest = 0;
802        $hid = 0;
803        $newBestCount = count($newBest);
804        for ($i = 0; $i < $newBestCount; $i++) {
805            if ($newBest[$i]['sum'] > $highest && $newBest[$i][0]['sid'] != 104 && $newBest[$i][0]['sid'] != 105 && $newBest[$i][0]['sid'] != 117) {
806                $yesterday = false;
807                $sCount = count($s);
808                for ($j = 0; $j < $sCount; $j++) {
809                    if ($newBest[$i][0]['tid'] == $s[$j]['Schedule']['tsumego_id']) {
810                        $yesterday = true;
811                    }
812                }
813                if (!$yesterday) {
814                    $highest = $newBest[$i]['sum'];
815                    $hid = $i;
816                }
817            }
818        }
819
820        return $newBest[$hid][0]['tid'];
821    }
822
823    protected function ratingMatch($elo) {
824        if ($elo >= 3000) {
825            $td = 10;//10d
826        } elseif ($elo >= 2900) {
827            $td = 10;//9d
828        } elseif ($elo >= 2800) {
829            $td = 10;//8d
830        } elseif ($elo >= 2700) {
831            $td = 10;//7d x2700
832        } elseif ($elo >= 2600) {
833            $td = 9;//6d x2600
834        } elseif ($elo >= 2500) {
835            $td = 8;//5d x2500
836        } elseif ($elo >= 2400) {
837            $td = 7;//4d
838        } elseif ($elo >= 2300) {
839            $td = 7;//3d x2350
840        } elseif ($elo >= 2200) {
841            $td = 6;//2d
842        } elseif ($elo >= 2100) {
843            $td = 6;//1d x2150
844        } elseif ($elo >= 2000) {
845            $td = 5;//1k
846        } elseif ($elo >= 1900) {
847            $td = 5;//2k x1950
848        } elseif ($elo >= 1800) {
849            $td = 4;//3k
850        } elseif ($elo >= 1700) {
851            $td = 4;//4k x1750
852        } elseif ($elo >= 1600) {
853            $td = 3;//5k
854        } elseif ($elo >= 1500) {
855            $td = 3;//6k x1500
856        } elseif ($elo >= 1400) {
857            $td = 3;//7k
858        } elseif ($elo >= 1300) {
859            $td = 2;//8k
860        } elseif ($elo >= 1200) {
861            $td = 2;//9k x1200
862        } elseif ($elo >= 1100) {
863            $td = 2;//10k
864        } elseif ($elo >= 1000) {
865            $td = 1;//11k
866        } elseif ($elo >= 900) {
867            $td = 1;//12k x900
868        } elseif ($elo >= 800) {
869            $td = 1;//13k
870        } elseif ($elo >= 700) {
871            $td = 1;//14k
872        } elseif ($elo >= 600) {
873            $td = 1;//15k
874        } elseif ($elo >= 500) {
875            $td = 1;//16k
876        } elseif ($elo >= 400) {
877            $td = 1;//17k
878        } elseif ($elo >= 300) {
879            $td = 1;//18k
880        } elseif ($elo >= 200) {
881            $td = 1;//19k
882        } elseif ($elo >= 100) {
883            $td = 1;//20k
884        } else {
885            $td = 1;
886        }
887
888        return $td;
889    }
890
891    protected function rating2($d) {
892        if ($d == 10) {
893            $elo = 2700;
894        } elseif ($d == 9) {
895            $elo = 2600;
896        } elseif ($d == 8) {
897            $elo = 2500;
898        } elseif ($d == 7) {
899            $elo = 2350;
900        } elseif ($d == 6) {
901            $elo = 2150;
902        } elseif ($d == 5) {
903            $elo = 1950;
904        } elseif ($d == 4) {
905            $elo = 1750;
906        } elseif ($d == 3) {
907            $elo = 1500;
908        } elseif ($d == 2) {
909            $elo = 1200;
910        } elseif ($d == 1) {
911            $elo = 900;
912        } else {
913            $elo = 1500;
914        }
915
916        return $elo;
917    }
918
919    public static function encrypt($str = null) {
920        $secret_key = 'my_simple_secret_keyx';
921        $secret_iv = 'my_simple_secret_ivx';
922        $encrypt_method = 'AES-256-CBC';
923        $key = hash('sha256', $secret_key);
924        $iv = substr(hash('sha256', $secret_iv), 0, 16);
925
926        return base64_encode(openssl_encrypt($str, $encrypt_method, $key, 0, $iv));
927    }
928
929    public static function decrypt($str = null) {
930        $string = $str;
931        $secret_key = 'my_simple_secret_keyx';
932        $secret_iv = 'my_simple_secret_ivx';
933        $encrypt_method = 'AES-256-CBC';
934        $key = hash('sha256', $secret_key);
935        $iv = substr(hash('sha256', $secret_iv), 0, 16);
936
937        return openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
938    }
939
940    protected function checkPictureLarge($u) {
941        if (substr($u['User']['name'], 0, 3) == 'g__' && $u['User']['external_id'] != null) {
942            return '<img class="google-profile-image-large" src="/img/google/' . $u['User']['picture'] . '">' . substr($u['User']['name'], 3);
943        }
944
945        return $u['User']['name'];
946    }
947    public static function checkPicture($user) {
948        if (substr($user['name'], 0, 3) == 'g__' && $user['external_id'] != null) {
949            return '<img class="google-profile-image" src="/img/google/' . $user['picture'] . '">' . substr($user['name'], 3);
950        }
951
952        return $user['name'];
953    }
954
955    public static function getTsumegoRankx($t) {
956        if ($t <= 0) {
957            return '15k';
958        }
959        if ($t > 0 && $t <= 22) {
960            $tRank = '5d';
961        } elseif ($t <= 26.5) {
962            $tRank = '4d';
963        } elseif ($t <= 30) {
964            $tRank = '3d';
965        } elseif ($t <= 34) {
966            $tRank = '2d';
967        } elseif ($t <= 38) {
968            $tRank = '1d';
969        } elseif ($t <= 42) {
970            $tRank = '1k';
971        } elseif ($t <= 46) {
972            $tRank = '2k';
973        } elseif ($t <= 50) {
974            $tRank = '3k';
975        } elseif ($t <= 54.5) {
976            $tRank = '4k';
977        } elseif ($t <= 58.5) {
978            $tRank = '5k';
979        } elseif ($t <= 63) {
980            $tRank = '6k';
981        } elseif ($t <= 67) {
982            $tRank = '7k';
983        } elseif ($t <= 70.8) {
984            $tRank = '8k';
985        } elseif ($t <= 74.8) {
986            $tRank = '9k';
987        } elseif ($t <= 79) {
988            $tRank = '10k';
989        } elseif ($t <= 83.5) {
990            $tRank = '11k';
991        } elseif ($t <= 88) {
992            $tRank = '12k';
993        } elseif ($t <= 92) {
994            $tRank = '13k';
995        } elseif ($t <= 96) {
996            $tRank = '14k';
997        } else {
998            $tRank = '15k';
999        }
1000
1001        return $tRank;
1002    }
1003    protected function adjustElo($v) {
1004        $add = 0;
1005        if ($v >= 1700) {
1006            $add = 110;
1007        } elseif ($v >= 1600) {
1008            $add = 110;
1009        } elseif ($v >= 1700) {
1010            $add = 100;
1011        } elseif ($v >= 1600) {
1012            $add = 90;
1013        } elseif ($v >= 1500) {
1014            $add = 80;
1015        } elseif ($v >= 1400) {
1016            $add = 70;
1017        } elseif ($v >= 1300) {
1018            $add = 60;
1019        } elseif ($v >= 1200) {
1020            $add = 60;
1021        } elseif ($v >= 1100) {
1022            $add = 50;
1023        } elseif ($v >= 1000) {
1024            $add = 50;
1025        } else {
1026            $add = 0;
1027        }
1028
1029        return $v + $add;
1030    }
1031
1032    public static function getTsumegoElo($rank, $p = null) {
1033        if ($p != null) {
1034            $p *= 100;
1035        } else {
1036            $p = 0;
1037        }
1038        $elo = 600;
1039        if ($rank == '9d') {
1040            $elo = round(2900 + $p);
1041        } elseif ($rank == '8d') {
1042            $elo = round(2800 + $p);
1043        } elseif ($rank == '7d') {
1044            $elo = round(2700 + $p);
1045        } elseif ($rank == '6d') {
1046            $elo = round(2600 + $p);
1047        } elseif ($rank == '5d') {
1048            $elo = round(2500 + $p);
1049        } elseif ($rank == '4d') {
1050            $elo = round(2400 + $p);
1051        } elseif ($rank == '3d') {
1052            $elo = round(2300 + $p);
1053        } elseif ($rank == '2d') {
1054            $elo = round(2200 + $p);
1055        } elseif ($rank == '1d') {
1056            $elo = round(2100 + $p);
1057        } elseif ($rank == '1k') {
1058            $elo = round(2000 + $p);
1059        } elseif ($rank == '2k') {
1060            $elo = round(1900 + $p);
1061        } elseif ($rank == '3k') {
1062            $elo = round(1800 + $p);
1063        } elseif ($rank == '4k') {
1064            $elo = round(1700 + $p);
1065        } elseif ($rank == '5k') {
1066            $elo = round(1600 + $p);
1067        } elseif ($rank == '6k') {
1068            $elo = round(1500 + $p);
1069        } elseif ($rank == '7k') {
1070            $elo = round(1400 + $p);
1071        } elseif ($rank == '8k') {
1072            $elo = round(1300 + $p);
1073        } elseif ($rank == '9k') {
1074            $elo = round(1200 + $p);
1075        } elseif ($rank == '10k') {
1076            $elo = round(1100 + $p);
1077        } elseif ($rank == '11k') {
1078            $elo = round(1000 + $p);
1079        } elseif ($rank == '12k') {
1080            $elo = round(900 + $p);
1081        } elseif ($rank == '13k') {
1082            $elo = round(800 + $p);
1083        } elseif ($rank == '14k') {
1084            $elo = round(700 + $p);
1085        } elseif ($rank == '15k' || $rank == '16k' || $rank == '17k' || $rank == '18k' || $rank == '19k' || $rank == '20k' || $rank == '21k') {
1086            $elo = round(600 + $p);
1087        }
1088
1089        return $elo;
1090    }
1091    protected function getTsumegoRankVal($t) {
1092        if ($t <= 0) {
1093            return 0;
1094        }
1095        if ($t > 0 && $t <= 22) {
1096            return 22 - $t;
1097        }
1098        if ($t <= 26.5) {
1099            return 26.5 - $t;
1100        }
1101        if ($t <= 30) {
1102            return 30 - $t;
1103        }
1104        if ($t <= 34) {
1105            return 34 - $t;
1106        }
1107        if ($t <= 38) {
1108            return 38 - $t;
1109        }
1110        if ($t <= 42) {
1111            return 42 - $t;
1112        }
1113        if ($t <= 46) {
1114            return 46 - $t;
1115        }
1116        if ($t <= 50) {
1117            return 50 - $t;
1118        }
1119        if ($t <= 54.5) {
1120            return 54.5 - $t;
1121        }
1122        if ($t <= 58.5) {
1123            return 58.5 - $t;
1124        }
1125        if ($t <= 63) {
1126            return 63 - $t;
1127        }
1128        if ($t <= 67) {
1129            return 67 - $t;
1130        }
1131        if ($t <= 70.8) {
1132            return 70.8 - $t;
1133        }
1134        if ($t <= 74.8) {
1135            return 74.8 - $t;
1136        }
1137        if ($t <= 79) {
1138            return 79 - $t;
1139        }
1140        if ($t <= 83.5) {
1141            return 83.5 - $t;
1142        }
1143        if ($t <= 88) {
1144            return 88 - $t;
1145        }
1146        if ($t <= 92) {
1147            return 92 - $t;
1148        }
1149        if ($t <= 96) {
1150            return 96 - $t;
1151        }
1152
1153        return 100 - $t;
1154    }
1155    protected function getTsumegoRankMax($t) {
1156        if ($t <= 0) {
1157            return 100 - 96;
1158        }
1159        if ($t > 0 && $t <= 22) {
1160            return 22;
1161        }
1162        if ($t <= 26.5) {
1163            return 26.5 - 22;
1164        }
1165        if ($t <= 30) {
1166            return 30 - 26.5;
1167        }
1168        if ($t <= 34) {
1169            return 34 - 30;
1170        }
1171        if ($t <= 38) {
1172            return 38 - 34;
1173        }
1174        if ($t <= 42) {
1175            return 42 - 38;
1176        }
1177        if ($t <= 46) {
1178            return 46 - 42;
1179        }
1180        if ($t <= 50) {
1181            return 50 - 46;
1182        }
1183        if ($t <= 54.5) {
1184            return 54.5 - 50;
1185        }
1186        if ($t <= 58.5) {
1187            return 58.5 - 54.5;
1188        }
1189        if ($t <= 63) {
1190            return 63 - 58.5;
1191        }
1192        if ($t <= 67) {
1193            return 67 - 63;
1194        }
1195        if ($t <= 70.8) {
1196            return 70.8 - 67;
1197        }
1198        if ($t <= 74.8) {
1199            return 74.8 - 70.8;
1200        }
1201        if ($t <= 79) {
1202            return 79 - 74.8;
1203        }
1204        if ($t <= 83.5) {
1205            return 83.5 - 79;
1206        }
1207        if ($t <= 88) {
1208            return 88 - 83.5;
1209        }
1210        if ($t <= 92) {
1211            return 92 - 88;
1212        }
1213        if ($t <= 96) {
1214            return 96 - 92;
1215        }
1216
1217        return 100 - 96;
1218    }
1219
1220    public static function saveDanSolveCondition($solvedTsumegoRank, $tId): void {
1221        if ($solvedTsumegoRank == '1d' || $solvedTsumegoRank == '2d' || $solvedTsumegoRank == '3d' || $solvedTsumegoRank == '4d' || $solvedTsumegoRank == '5d') {
1222            $danSolveCategory = 'danSolve' . $solvedTsumegoRank;
1223            $danSolveCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1224                'order' => 'value DESC',
1225                'conditions' => [
1226                    'user_id' => Auth::getUserID(),
1227                    'category' => $danSolveCategory,
1228                ],
1229            ]);
1230            if (!$danSolveCondition) {
1231                $danSolveCondition = [];
1232                $danSolveCondition['AchievementCondition']['value'] = 0;
1233                ClassRegistry::init('AchievementCondition')->create();
1234            }
1235            $danSolveCondition['AchievementCondition']['category'] = $danSolveCategory;
1236            $danSolveCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1237            $danSolveCondition['AchievementCondition']['set_id'] = $tId;
1238            $danSolveCondition['AchievementCondition']['value']++;
1239
1240            ClassRegistry::init('AchievementCondition')->save($danSolveCondition);
1241        }
1242    }
1243
1244    public static function updateSprintCondition(bool $trigger = false): void {
1245        if (Auth::isLoggedIn()) {
1246            $sprintCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1247                'order' => 'value DESC',
1248                'conditions' => [
1249                    'user_id' => Auth::getUserID(),
1250                    'category' => 'sprint',
1251                ],
1252            ]);
1253            if (!$sprintCondition) {
1254                $sprintCondition = [];
1255                $sprintCondition['AchievementCondition']['value'] = 0;
1256                ClassRegistry::init('AchievementCondition')->create();
1257            }
1258            $sprintCondition['AchievementCondition']['category'] = 'sprint';
1259            $sprintCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1260            if ($trigger) {
1261                $sprintCondition['AchievementCondition']['value']++;
1262            } else {
1263                $sprintCondition['AchievementCondition']['value'] = 0;
1264            }
1265            ClassRegistry::init('AchievementCondition')->save($sprintCondition);
1266        }
1267    }
1268
1269    public static function updateGoldenCondition(bool $trigger = false): void {
1270        $goldenCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1271            'order' => 'value DESC',
1272            'conditions' => [
1273                'user_id' => Auth::getUserID(),
1274                'category' => 'golden',
1275            ],
1276        ]);
1277        if (!$goldenCondition) {
1278            $goldenCondition = [];
1279            $goldenCondition['AchievementCondition']['value'] = 0;
1280            ClassRegistry::init('AchievementCondition')->create();
1281        }
1282        $goldenCondition['AchievementCondition']['category'] = 'golden';
1283        $goldenCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1284        if ($trigger) {
1285            $goldenCondition['AchievementCondition']['value']++;
1286        } else {
1287            $goldenCondition['AchievementCondition']['value'] = 0;
1288        }
1289        ClassRegistry::init('AchievementCondition')->save($goldenCondition);
1290    }
1291
1292    public static function setPotionCondition(): void {
1293        $potionCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1294            'order' => 'value DESC',
1295            'conditions' => [
1296                'user_id' => Auth::getUserID(),
1297                'category' => 'potion',
1298            ],
1299        ]);
1300        if (!$potionCondition) {
1301            $potionCondition = [];
1302            ClassRegistry::init('AchievementCondition')->create();
1303        }
1304        $potionCondition['AchievementCondition']['category'] = 'potion';
1305        $potionCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1306        $potionCondition['AchievementCondition']['value'] = 1;
1307        ClassRegistry::init('AchievementCondition')->save($potionCondition);
1308    }
1309
1310    public static function updateGems(string $rank): void {
1311        $datex = new DateTime('today');
1312        $dateGem = ClassRegistry::init('DayRecord')->find('first', ['conditions' => ['date' => $datex->format('Y-m-d')]]);
1313        if ($dateGem != null) {
1314            $gems = explode('-', $dateGem['DayRecord']['gems']);
1315            $gemValue = '';
1316            $gemValue2 = '';
1317            $gemValue3 = '';
1318            $condition1 = 500;
1319            $condition2 = 200;
1320            $condition3 = 5;
1321            $found1 = false;
1322            $found2 = false;
1323            $found3 = false;
1324            if ($rank == '15k' || $rank == '14k' || $rank == '13k' || $rank == '12k' || $rank == '11k' || $rank == '10k') {
1325                if ($gems[0] == 0) {
1326                    $gemValue = '15k';
1327                } elseif ($gems[0] == 1) {
1328                    $gemValue = '12k';
1329                } elseif ($gems[0] == 2) {
1330                    $gemValue = '10k';
1331                }
1332                if ($rank == $gemValue) {
1333                    $dateGem['DayRecord']['gemCounter1']++;
1334                    if ($dateGem['DayRecord']['gemCounter1'] == $condition1) {
1335                        $found1 = true;
1336                    }
1337                }
1338            } elseif ($rank == '9k' || $rank == '8k' || $rank == '7k' || $rank == '6k' || $rank == '5k' || $rank == '4k' || $rank == '3k' || $rank == '2k' || $rank == '1k') {
1339                if ($gems[1] == 0) {
1340                    $gemValue = '9k';
1341                    $gemValue2 = 'x';
1342                    $gemValue3 = 'y';
1343                } elseif ($gems[1] == 1) {
1344                    $gemValue = '6k';
1345                    $gemValue2 = '5k';
1346                    $gemValue3 = '4k';
1347                } elseif ($gems[1] == 2) {
1348                    $gemValue = 'x';
1349                    $gemValue2 = '2k';
1350                    $gemValue3 = '1k';
1351                }
1352                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1353                    $dateGem['DayRecord']['gemCounter2']++;
1354                    if ($dateGem['DayRecord']['gemCounter2'] == $condition2) {
1355                        $found2 = true;
1356                    }
1357                }
1358            } elseif ($rank == '1d' || $rank == '2d' || $rank == '3d' || $rank == '4d' || $rank == '5d' || $rank == '6d' || $rank == '7d') {
1359                if ($gems[2] == 0) {
1360                    $gemValue = '1d';
1361                    $gemValue2 = '2d';
1362                    $gemValue3 = '3d';
1363                } elseif ($gems[2] == 1) {
1364                    $gemValue = '2d';
1365                    $gemValue2 = '3d';
1366                    $gemValue3 = '4d';
1367                } elseif ($gems[2] == 2) {
1368                    $gemValue = '5d';
1369                    $gemValue2 = '6d';
1370                    $gemValue3 = '7d';
1371                }
1372                if ($rank == $gemValue || $rank == $gemValue2 || $rank == $gemValue3) {
1373                    $dateGem['DayRecord']['gemCounter3']++;
1374                    if ($dateGem['DayRecord']['gemCounter3'] == $condition3) {
1375                        $found3 = true;
1376                    }
1377                }
1378            }
1379            if ($found1) {
1380                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1381                    'order' => 'value DESC',
1382                    'conditions' => [
1383                        'user_id' => Auth::getUserID(),
1384                        'category' => 'emerald',
1385                    ],
1386                ]);
1387                if ($aCondition == null) {
1388                    $aCondition = [];
1389                    $aCondition['AchievementCondition']['category'] = 'emerald';
1390                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1391                    $aCondition['AchievementCondition']['value'] = 1;
1392                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1393                } else {
1394                    $dateGem['DayRecord']['gemCounter1']--;
1395                }
1396            } elseif ($found2) {
1397                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1398                    'order' => 'value DESC',
1399                    'conditions' => [
1400                        'user_id' => Auth::getUserID(),
1401                        'category' => 'sapphire',
1402                    ],
1403                ]);
1404                if ($aCondition == null) {
1405                    $aCondition = [];
1406                    $aCondition['AchievementCondition']['category'] = 'sapphire';
1407                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1408                    $aCondition['AchievementCondition']['value'] = 1;
1409                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1410                } else {
1411                    $dateGem['DayRecord']['gemCounter2']--;
1412                }
1413            } elseif ($found3) {
1414                $aCondition = ClassRegistry::init('AchievementCondition')->find('first', [
1415                    'order' => 'value DESC',
1416                    'conditions' => [
1417                        'user_id' => Auth::getUserID(),
1418                        'category' => 'ruby',
1419                    ],
1420                ]);
1421                if ($aCondition == null) {
1422                    $aCondition = [];
1423                    $aCondition['AchievementCondition']['category'] = 'ruby';
1424                    $aCondition['AchievementCondition']['user_id'] = Auth::getUserID();
1425                    $aCondition['AchievementCondition']['value'] = 1;
1426                    ClassRegistry::init('AchievementCondition')->save($aCondition);
1427                } else {
1428                    $dateGem['DayRecord']['gemCounter3']--;
1429                }
1430            }
1431        }
1432        ClassRegistry::init('DayRecord')->save($dateGem);
1433    }
1434
1435    public static function checkProblemNumberAchievements() {
1436        if (!Auth::isLoggedIn()) {
1437            return;
1438        }
1439
1440        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1441        if (!$buffer) {
1442            $buffer = [];
1443        }
1444        $existingAs = [];
1445        $bufferCount = count($buffer);
1446        for ($i = 0; $i < $bufferCount; $i++) {
1447            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1448        }
1449        $as = [];
1450        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1451        $updated = [];
1452
1453        $achievementId = 1;
1454        $solvedCount = Auth::getUser()['solved'];
1455        if ($solvedCount >= 1000 && !isset($existingAs[$achievementId])) {
1456            $as['AchievementStatus']['achievement_id'] = $achievementId;
1457            ClassRegistry::init('AchievementStatus')->create();
1458            ClassRegistry::init('AchievementStatus')->save($as);
1459            array_push($updated, $achievementId);
1460        }
1461        $achievementId = 2;
1462        if ($solvedCount >= 2000 && !isset($existingAs[$achievementId])) {
1463            $as['AchievementStatus']['achievement_id'] = $achievementId;
1464            ClassRegistry::init('AchievementStatus')->create();
1465            ClassRegistry::init('AchievementStatus')->save($as);
1466            array_push($updated, $achievementId);
1467        }
1468        $achievementId = 3;
1469        if ($solvedCount >= 3000 && !isset($existingAs[$achievementId])) {
1470            $as['AchievementStatus']['achievement_id'] = $achievementId;
1471            ClassRegistry::init('AchievementStatus')->create();
1472            ClassRegistry::init('AchievementStatus')->save($as);
1473            array_push($updated, $achievementId);
1474        }
1475        $achievementId = 4;
1476        if ($solvedCount >= 4000 && !isset($existingAs[$achievementId])) {
1477            $as['AchievementStatus']['achievement_id'] = $achievementId;
1478            ClassRegistry::init('AchievementStatus')->create();
1479            ClassRegistry::init('AchievementStatus')->save($as);
1480            array_push($updated, $achievementId);
1481        }
1482        $achievementId = 5;
1483        if ($solvedCount >= 5000 && !isset($existingAs[$achievementId])) {
1484            $as['AchievementStatus']['achievement_id'] = $achievementId;
1485            ClassRegistry::init('AchievementStatus')->create();
1486            ClassRegistry::init('AchievementStatus')->save($as);
1487            array_push($updated, $achievementId);
1488        }
1489        $achievementId = 6;
1490        if ($solvedCount >= 6000 && !isset($existingAs[$achievementId])) {
1491            $as['AchievementStatus']['achievement_id'] = $achievementId;
1492            ClassRegistry::init('AchievementStatus')->create();
1493            ClassRegistry::init('AchievementStatus')->save($as);
1494            array_push($updated, $achievementId);
1495        }
1496        $achievementId = 7;
1497        if ($solvedCount >= 7000 && !isset($existingAs[$achievementId])) {
1498            $as['AchievementStatus']['achievement_id'] = $achievementId;
1499            ClassRegistry::init('AchievementStatus')->create();
1500            ClassRegistry::init('AchievementStatus')->save($as);
1501            array_push($updated, $achievementId);
1502        }
1503        $achievementId = 8;
1504        if ($solvedCount >= 8000 && !isset($existingAs[$achievementId])) {
1505            $as['AchievementStatus']['achievement_id'] = $achievementId;
1506            ClassRegistry::init('AchievementStatus')->create();
1507            ClassRegistry::init('AchievementStatus')->save($as);
1508            array_push($updated, $achievementId);
1509        }
1510        $achievementId = 9;
1511        if ($solvedCount >= 9000 && !isset($existingAs[$achievementId])) {
1512            $as['AchievementStatus']['achievement_id'] = $achievementId;
1513            ClassRegistry::init('AchievementStatus')->create();
1514            ClassRegistry::init('AchievementStatus')->save($as);
1515            array_push($updated, $achievementId);
1516        }
1517        $achievementId = 10;
1518        if ($solvedCount >= 10000 && !isset($existingAs[$achievementId])) {
1519            $as['AchievementStatus']['achievement_id'] = $achievementId;
1520            ClassRegistry::init('AchievementStatus')->create();
1521            ClassRegistry::init('AchievementStatus')->save($as);
1522            array_push($updated, $achievementId);
1523        }
1524        //uotd achievement
1525        $achievementId = 11;
1526        if (!isset($existingAs[$achievementId])) {
1527            $condition = ClassRegistry::init('AchievementCondition')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => 'uotd']]);
1528            if ($condition != null) {
1529                $as['AchievementStatus']['achievement_id'] = $achievementId;
1530                ClassRegistry::init('AchievementStatus')->create();
1531                ClassRegistry::init('AchievementStatus')->save($as);
1532                array_push($updated, $achievementId);
1533            }
1534        }
1535
1536        $updatedCount = count($updated);
1537        for ($i = 0; $i < $updatedCount; $i++) {
1538            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1539            $updated[$i] = [];
1540            $updated[$i][0] = $a['Achievement']['name'];
1541            $updated[$i][1] = $a['Achievement']['description'];
1542            $updated[$i][2] = $a['Achievement']['image'];
1543            $updated[$i][3] = $a['Achievement']['color'];
1544            $updated[$i][4] = $a['Achievement']['xp'];
1545            $updated[$i][5] = $a['Achievement']['id'];
1546        }
1547
1548        return $updated;
1549    }
1550
1551    public static function checkDanSolveAchievements() {
1552        if (Auth::isLoggedIn()) {
1553            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1554            if (!$buffer) {
1555                $buffer = [];
1556            }
1557            $ac = ClassRegistry::init('AchievementCondition')->find('all', [
1558                'order' => 'category ASC',
1559                'conditions' => [
1560                    'user_id' => Auth::getUserID(),
1561                    'OR' => [
1562                        ['category' => 'danSolve1d'],
1563                        ['category' => 'danSolve2d'],
1564                        ['category' => 'danSolve3d'],
1565                        ['category' => 'danSolve4d'],
1566                        ['category' => 'danSolve5d'],
1567                        ['category' => 'emerald'],
1568                        ['category' => 'sapphire'],
1569                        ['category' => 'ruby'],
1570                        ['category' => 'sprint'],
1571                        ['category' => 'golden'],
1572                        ['category' => 'potion'],
1573                    ],
1574                ],
1575            ]);
1576            if (!$ac) {
1577                $ac = [];
1578            }
1579            $ac1 = [];
1580            $acCount = count($ac);
1581            for ($i = 0; $i < $acCount; $i++) {
1582                if ($ac[$i]['AchievementCondition']['category'] == 'danSolve1d') {
1583                    $ac1['1d'] = $ac[$i]['AchievementCondition']['value'];
1584                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve2d') {
1585                    $ac1['2d'] = $ac[$i]['AchievementCondition']['value'];
1586                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve3d') {
1587                    $ac1['3d'] = $ac[$i]['AchievementCondition']['value'];
1588                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve4d') {
1589                    $ac1['4d'] = $ac[$i]['AchievementCondition']['value'];
1590                } elseif ($ac[$i]['AchievementCondition']['category'] == 'danSolve5d') {
1591                    $ac1['5d'] = $ac[$i]['AchievementCondition']['value'];
1592                } elseif ($ac[$i]['AchievementCondition']['category'] == 'emerald') {
1593                    $ac1['emerald'] = $ac[$i]['AchievementCondition']['value'];
1594                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sapphire') {
1595                    $ac1['sapphire'] = $ac[$i]['AchievementCondition']['value'];
1596                } elseif ($ac[$i]['AchievementCondition']['category'] == 'ruby') {
1597                    $ac1['ruby'] = $ac[$i]['AchievementCondition']['value'];
1598                } elseif ($ac[$i]['AchievementCondition']['category'] == 'sprint') {
1599                    $ac1['sprint'] = $ac[$i]['AchievementCondition']['value'];
1600                } elseif ($ac[$i]['AchievementCondition']['category'] == 'golden') {
1601                    $ac1['golden'] = $ac[$i]['AchievementCondition']['value'];
1602                } elseif ($ac[$i]['AchievementCondition']['category'] == 'potion') {
1603                    $ac1['potion'] = $ac[$i]['AchievementCondition']['value'];
1604                }
1605            }
1606
1607            $existingAs = [];
1608            $bufferCount = count($buffer);
1609            for ($i = 0; $i < $bufferCount; $i++) {
1610                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1611            }
1612            $as = [];
1613            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1614            $updated = [];
1615            $achievementId = 101;
1616            if ($ac1['1d'] > 0 && !isset($existingAs[$achievementId])) {
1617                $as['AchievementStatus']['achievement_id'] = $achievementId;
1618                ClassRegistry::init('AchievementStatus')->create();
1619                ClassRegistry::init('AchievementStatus')->save($as);
1620                array_push($updated, $achievementId);
1621            }
1622            $achievementId = 102;
1623            if ($ac1['2d'] > 0 && !isset($existingAs[$achievementId])) {
1624                $as['AchievementStatus']['achievement_id'] = $achievementId;
1625                ClassRegistry::init('AchievementStatus')->create();
1626                ClassRegistry::init('AchievementStatus')->save($as);
1627                array_push($updated, $achievementId);
1628            }
1629            $achievementId = 103;
1630            if ($ac1['3d'] > 0 && !isset($existingAs[$achievementId])) {
1631                $as['AchievementStatus']['achievement_id'] = $achievementId;
1632                ClassRegistry::init('AchievementStatus')->create();
1633                ClassRegistry::init('AchievementStatus')->save($as);
1634                array_push($updated, $achievementId);
1635            }
1636            $achievementId = 104;
1637            if ($ac1['4d'] > 0 && !isset($existingAs[$achievementId])) {
1638                $as['AchievementStatus']['achievement_id'] = $achievementId;
1639                ClassRegistry::init('AchievementStatus')->create();
1640                ClassRegistry::init('AchievementStatus')->save($as);
1641                array_push($updated, $achievementId);
1642            }
1643            $achievementId = 105;
1644            if ($ac1['5d'] > 0 && !isset($existingAs[$achievementId])) {
1645                $as['AchievementStatus']['achievement_id'] = $achievementId;
1646                ClassRegistry::init('AchievementStatus')->create();
1647                ClassRegistry::init('AchievementStatus')->save($as);
1648                array_push($updated, $achievementId);
1649            }
1650            $achievementId = 106;
1651            if ($ac1['1d'] >= 10 && !isset($existingAs[$achievementId])) {
1652                $as['AchievementStatus']['achievement_id'] = $achievementId;
1653                ClassRegistry::init('AchievementStatus')->create();
1654                ClassRegistry::init('AchievementStatus')->save($as);
1655                array_push($updated, $achievementId);
1656            }
1657            $achievementId = 107;
1658            if ($ac1['2d'] >= 10 && !isset($existingAs[$achievementId])) {
1659                $as['AchievementStatus']['achievement_id'] = $achievementId;
1660                ClassRegistry::init('AchievementStatus')->create();
1661                ClassRegistry::init('AchievementStatus')->save($as);
1662                array_push($updated, $achievementId);
1663            }
1664            $achievementId = 108;
1665            if ($ac1['3d'] >= 10 && !isset($existingAs[$achievementId])) {
1666                $as['AchievementStatus']['achievement_id'] = $achievementId;
1667                ClassRegistry::init('AchievementStatus')->create();
1668                ClassRegistry::init('AchievementStatus')->save($as);
1669                array_push($updated, $achievementId);
1670            }
1671            $achievementId = 109;
1672            if ($ac1['4d'] >= 10 && !isset($existingAs[$achievementId])) {
1673                $as['AchievementStatus']['achievement_id'] = $achievementId;
1674                ClassRegistry::init('AchievementStatus')->create();
1675                ClassRegistry::init('AchievementStatus')->save($as);
1676                array_push($updated, $achievementId);
1677            }
1678            $achievementId = 110;
1679            if ($ac1['5d'] >= 10 && !isset($existingAs[$achievementId])) {
1680                $as['AchievementStatus']['achievement_id'] = $achievementId;
1681                ClassRegistry::init('AchievementStatus')->create();
1682                ClassRegistry::init('AchievementStatus')->save($as);
1683                array_push($updated, $achievementId);
1684            }
1685            $achievementId = 111;
1686            if (isset($ac1['emerald'])) {
1687                if ($ac1['emerald'] == 1 && !isset($existingAs[$achievementId])) {
1688                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1689                    ClassRegistry::init('AchievementStatus')->create();
1690                    ClassRegistry::init('AchievementStatus')->save($as);
1691                    array_push($updated, $achievementId);
1692                }
1693            }
1694            $achievementId = 112;
1695            if (isset($ac1['sapphire'])) {
1696                if ($ac1['sapphire'] == 1 && !isset($existingAs[$achievementId])) {
1697                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1698                    ClassRegistry::init('AchievementStatus')->create();
1699                    ClassRegistry::init('AchievementStatus')->save($as);
1700                    array_push($updated, $achievementId);
1701                }
1702            }
1703            $achievementId = 113;
1704            if (isset($ac1['ruby'])) {
1705                if ($ac1['ruby'] == 1 && !isset($existingAs[$achievementId])) {
1706                    $as['AchievementStatus']['achievement_id'] = $achievementId;
1707                    ClassRegistry::init('AchievementStatus')->create();
1708                    ClassRegistry::init('AchievementStatus')->save($as);
1709                    array_push($updated, $achievementId);
1710                }
1711            }
1712            $achievementId = 114;
1713            if (!isset($existingAs[$achievementId]) && isset($existingAs[111]) && isset($existingAs[112]) && isset($existingAs[113])) {
1714                $as['AchievementStatus']['achievement_id'] = $achievementId;
1715                ClassRegistry::init('AchievementStatus')->create();
1716                ClassRegistry::init('AchievementStatus')->save($as);
1717                array_push($updated, $achievementId);
1718            }
1719            $achievementId = 96;
1720            if (!isset($existingAs[$achievementId]) && $ac1['sprint'] >= 30) {
1721                $as['AchievementStatus']['achievement_id'] = $achievementId;
1722                ClassRegistry::init('AchievementStatus')->create();
1723                ClassRegistry::init('AchievementStatus')->save($as);
1724                array_push($updated, $achievementId);
1725            }
1726            $achievementId = 97;
1727            if (!isset($existingAs[$achievementId]) && $ac1['golden'] >= 10) {
1728                $as['AchievementStatus']['achievement_id'] = $achievementId;
1729                ClassRegistry::init('AchievementStatus')->create();
1730                ClassRegistry::init('AchievementStatus')->save($as);
1731                array_push($updated, $achievementId);
1732            }
1733            $achievementId = 98;
1734            if (!isset($existingAs[$achievementId]) && $ac1['potion'] >= 1) {
1735                $as['AchievementStatus']['achievement_id'] = $achievementId;
1736                ClassRegistry::init('AchievementStatus')->create();
1737                ClassRegistry::init('AchievementStatus')->save($as);
1738                array_push($updated, $achievementId);
1739            }
1740            $updatedCount = count($updated);
1741            for ($i = 0; $i < $updatedCount; $i++) {
1742                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1743                $updated[$i] = [];
1744                $updated[$i][0] = $a['Achievement']['name'];
1745                $updated[$i][1] = $a['Achievement']['description'];
1746                $updated[$i][2] = $a['Achievement']['image'];
1747                $updated[$i][3] = $a['Achievement']['color'];
1748                $updated[$i][4] = $a['Achievement']['xp'];
1749                $updated[$i][5] = $a['Achievement']['id'];
1750            }
1751
1752            return $updated;
1753        }
1754    }
1755
1756    protected function checkForLocked($t, $setsWithPremium) {
1757        $scCheck = $this->SetConnection->find('first', ['conditions' => ['tsumego_id' => $t['Tsumego']['id']]]);
1758        if ($scCheck && in_array($scCheck['SetConnection']['set_id'], $setsWithPremium) && !Auth::hasPremium()) {
1759            $t['Tsumego']['locked'] = true;
1760        } else {
1761            $t['Tsumego']['locked'] = false;
1762        }
1763
1764        return $t;
1765    }
1766    public static function checkNoErrorAchievements() {
1767        if (Auth::isLoggedIn()) {
1768
1769            $ac = ClassRegistry::init('AchievementCondition')->find('first', [
1770                'order' => 'value DESC',
1771                'conditions' => [
1772                    'user_id' => Auth::getUserID(),
1773                    'category' => 'err',
1774                ],
1775            ]);
1776
1777            $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1778            if (!$buffer) {
1779                $buffer = [];
1780            }
1781            $existingAs = [];
1782            $bufferCount = count($buffer);
1783            for ($i = 0; $i < $bufferCount; $i++) {
1784                $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1785            }
1786            $as = [];
1787            $as['AchievementStatus']['user_id'] = Auth::getUserID();
1788            $updated = [];
1789
1790            $achievementId = 53;
1791            if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
1792                $as['AchievementStatus']['achievement_id'] = $achievementId;
1793                ClassRegistry::init('AchievementStatus')->create();
1794                ClassRegistry::init('AchievementStatus')->save($as);
1795                array_push($updated, $achievementId);
1796            }
1797            $achievementId = 54;
1798            if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
1799                $as['AchievementStatus']['achievement_id'] = $achievementId;
1800                ClassRegistry::init('AchievementStatus')->create();
1801                ClassRegistry::init('AchievementStatus')->save($as);
1802                array_push($updated, $achievementId);
1803            }
1804            $achievementId = 55;
1805            if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
1806                $as['AchievementStatus']['achievement_id'] = $achievementId;
1807                ClassRegistry::init('AchievementStatus')->create();
1808                ClassRegistry::init('AchievementStatus')->save($as);
1809                array_push($updated, $achievementId);
1810            }
1811            $achievementId = 56;
1812            if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
1813                $as['AchievementStatus']['achievement_id'] = $achievementId;
1814                ClassRegistry::init('AchievementStatus')->create();
1815                ClassRegistry::init('AchievementStatus')->save($as);
1816                array_push($updated, $achievementId);
1817            }
1818            $achievementId = 57;
1819            if ($ac['AchievementCondition']['value'] >= 100 && !isset($existingAs[$achievementId])) {
1820                $as['AchievementStatus']['achievement_id'] = $achievementId;
1821                ClassRegistry::init('AchievementStatus')->create();
1822                ClassRegistry::init('AchievementStatus')->save($as);
1823                array_push($updated, $achievementId);
1824            }
1825            $achievementId = 58;
1826            if ($ac['AchievementCondition']['value'] >= 200 && !isset($existingAs[$achievementId])) {
1827                $as['AchievementStatus']['achievement_id'] = $achievementId;
1828                ClassRegistry::init('AchievementStatus')->create();
1829                ClassRegistry::init('AchievementStatus')->save($as);
1830                array_push($updated, $achievementId);
1831            }
1832            $updatedCount = count($updated);
1833            for ($i = 0; $i < $updatedCount; $i++) {
1834                $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1835                $updated[$i] = [];
1836                $updated[$i][0] = $a['Achievement']['name'];
1837                $updated[$i][1] = $a['Achievement']['description'];
1838                $updated[$i][2] = $a['Achievement']['image'];
1839                $updated[$i][3] = $a['Achievement']['color'];
1840                $updated[$i][4] = $a['Achievement']['xp'];
1841                $updated[$i][5] = $a['Achievement']['id'];
1842            }
1843
1844            return $updated;
1845        }
1846    }
1847
1848    protected function checkTimeModeAchievements() {
1849        $this->loadModel('Achievement');
1850        $this->loadModel('AchievementStatus');
1851        $this->loadModel('TimeModeSession');
1852
1853        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1854        if (!$buffer) {
1855            $buffer = [];
1856        }
1857        $existingAs = [];
1858        $bufferCount = count($buffer);
1859        for ($i = 0; $i < $bufferCount; $i++) {
1860            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
1861        }
1862        $as = [];
1863        $as['AchievementStatus']['user_id'] = Auth::getUserID();
1864        $updated = [];
1865
1866        $rBlitz = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_BLITZ, 'user_id' => Auth::getUserID()]]);
1867        if (!$rBlitz) {
1868            $rBlitz = [];
1869        }
1870        $rFast = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_FAST_SPEED, 'user_id' => Auth::getUserID()]]);
1871        if (!$rFast) {
1872            $rFast = [];
1873        }
1874        $rSlow = $this->TimeModeSession->find('all', ['conditions' => ['time_mode_category_id' => TimeModeUtil::$CATEGORY_SLOW_SPEED, 'user_id' => Auth::getUserID()]]);
1875        if (!$rSlow) {
1876            $rSlow = [];
1877        }
1878        $r = $this->TimeModeSession->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1879        if (!$r) {
1880            $r = [];
1881        }
1882
1883        $timeModeAchievements = [];
1884        for ($i = 70; $i <= 91; $i++) {
1885            $timeModeAchievements[$i] = false;
1886        }
1887        $rCount = count($r);
1888        for ($i = 0; $i < $rCount; $i++) {
1889            if ($r[$i]['TimeModeSession']['status'] == 's') {
1890                if ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k') {
1891                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1892                        $timeModeAchievements[70] = true;
1893                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1894                        $timeModeAchievements[76] = true;
1895                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1896                        $timeModeAchievements[82] = true;
1897                    }
1898                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k') {
1899                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1900                        $timeModeAchievements[71] = true;
1901                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1902                        $timeModeAchievements[77] = true;
1903                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1904                        $timeModeAchievements[83] = true;
1905                    }
1906                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k') {
1907                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1908                        $timeModeAchievements[72] = true;
1909                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1910                        $timeModeAchievements[78] = true;
1911                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1912                        $timeModeAchievements[84] = true;
1913                    }
1914                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k') {
1915                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1916                        $timeModeAchievements[73] = true;
1917                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1918                        $timeModeAchievements[79] = true;
1919                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1920                        $timeModeAchievements[85] = true;
1921                    }
1922                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k') {
1923                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1924                        $timeModeAchievements[74] = true;
1925                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1926                        $timeModeAchievements[80] = true;
1927                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1928                        $timeModeAchievements[86] = true;
1929                    }
1930                } elseif ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d') {
1931                    if ($r[$i]['TimeModeSession']['mode'] == 2) {
1932                        $timeModeAchievements[75] = true;
1933                    } elseif ($r[$i]['TimeModeSession']['mode'] == 1) {
1934                        $timeModeAchievements[81] = true;
1935                    } elseif ($r[$i]['TimeModeSession']['mode'] == 0) {
1936                        $timeModeAchievements[87] = true;
1937                    }
1938                }
1939            }
1940            if ($r[$i]['TimeModeSession']['points'] >= 850
1941            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1942            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1943            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d')) {
1944                $timeModeAchievements[91] = true;
1945            }
1946            if ($r[$i]['TimeModeSession']['points'] >= 875
1947            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1948            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1949            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k')) {
1950                $timeModeAchievements[90] = true;
1951            }
1952            if ($r[$i]['TimeModeSession']['points'] >= 900
1953            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1954            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1955            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
1956            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k')) {
1957                $timeModeAchievements[89] = true;
1958            }
1959            if ($r[$i]['TimeModeSession']['points'] >= 950
1960            && ($r[$i]['TimeModeSession']['TimeModeAttempt'] == '4k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1k'
1961            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '1d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '2d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '3d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '4d'
1962            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5d' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '5k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '6k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '7k'
1963            || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '8k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '9k' || $r[$i]['TimeModeSession']['TimeModeAttempt'] == '10k')) {
1964                $timeModeAchievements[88] = true;
1965            }
1966        }
1967        for ($i = 70; $i <= 91; $i++) {
1968            $achievementId = $i;
1969            if ($timeModeAchievements[$achievementId] == true && !isset($existingAs[$achievementId])) {
1970                $as['AchievementStatus']['achievement_id'] = $achievementId;
1971                ClassRegistry::init('AchievementStatus')->create();
1972                ClassRegistry::init('AchievementStatus')->save($as);
1973                array_push($updated, $achievementId);
1974            }
1975        }
1976        $updatedCount = count($updated);
1977        for ($i = 0; $i < $updatedCount; $i++) {
1978            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
1979            $updated[$i] = [];
1980            $updated[$i][0] = $a['Achievement']['name'];
1981            $updated[$i][1] = $a['Achievement']['description'];
1982            $updated[$i][2] = $a['Achievement']['image'];
1983            $updated[$i][3] = $a['Achievement']['color'];
1984            $updated[$i][4] = $a['Achievement']['xp'];
1985            $updated[$i][5] = $a['Achievement']['id'];
1986        }
1987
1988        return $updated;
1989    }
1990
1991    public static function checkRatingAchievements() {
1992        if (!Auth::isLoggedIn()) {
1993            return;
1994        }
1995
1996        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
1997        if (!$buffer) {
1998            $buffer = [];
1999        }
2000        $existingAs = [];
2001        $bufferCount = count($buffer);
2002        for ($i = 0; $i < $bufferCount; $i++) {
2003            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2004        }
2005        $as = [];
2006        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2007        $updated = [];
2008
2009        $achievementId = 59;
2010        $currentElo = Auth::getUser()['rating'];
2011        if ($currentElo >= 1500 && !isset($existingAs[$achievementId])) {
2012            $as['AchievementStatus']['achievement_id'] = $achievementId;
2013            ClassRegistry::init('AchievementStatus')->create();
2014            ClassRegistry::init('AchievementStatus')->save($as);
2015            array_push($updated, $achievementId);
2016        }
2017        $achievementId = 60;
2018        if ($currentElo >= 1600 && !isset($existingAs[$achievementId])) {
2019            $as['AchievementStatus']['achievement_id'] = $achievementId;
2020            ClassRegistry::init('AchievementStatus')->create();
2021            ClassRegistry::init('AchievementStatus')->save($as);
2022            array_push($updated, $achievementId);
2023        }
2024        $achievementId = 61;
2025        if ($currentElo >= 1700 && !isset($existingAs[$achievementId])) {
2026            $as['AchievementStatus']['achievement_id'] = $achievementId;
2027            ClassRegistry::init('AchievementStatus')->create();
2028            ClassRegistry::init('AchievementStatus')->save($as);
2029            array_push($updated, $achievementId);
2030        }
2031        $achievementId = 62;
2032        if ($currentElo >= 1800 && !isset($existingAs[$achievementId])) {
2033            $as['AchievementStatus']['achievement_id'] = $achievementId;
2034            ClassRegistry::init('AchievementStatus')->create();
2035            ClassRegistry::init('AchievementStatus')->save($as);
2036            array_push($updated, $achievementId);
2037        }
2038        $achievementId = 63;
2039        if ($currentElo >= 1900 && !isset($existingAs[$achievementId])) {
2040            $as['AchievementStatus']['achievement_id'] = $achievementId;
2041            ClassRegistry::init('AchievementStatus')->create();
2042            ClassRegistry::init('AchievementStatus')->save($as);
2043            array_push($updated, $achievementId);
2044        }
2045        $achievementId = 64;
2046        if ($currentElo >= 2000 && !isset($existingAs[$achievementId])) {
2047            $as['AchievementStatus']['achievement_id'] = $achievementId;
2048            ClassRegistry::init('AchievementStatus')->create();
2049            ClassRegistry::init('AchievementStatus')->save($as);
2050            array_push($updated, $achievementId);
2051        }
2052        $achievementId = 65;
2053        if ($currentElo >= 2100 && !isset($existingAs[$achievementId])) {
2054            $as['AchievementStatus']['achievement_id'] = $achievementId;
2055            ClassRegistry::init('AchievementStatus')->create();
2056            ClassRegistry::init('AchievementStatus')->save($as);
2057            array_push($updated, $achievementId);
2058        }
2059        $achievementId = 66;
2060        if ($currentElo >= 2200 && !isset($existingAs[$achievementId])) {
2061            $as['AchievementStatus']['achievement_id'] = $achievementId;
2062            ClassRegistry::init('AchievementStatus')->create();
2063            ClassRegistry::init('AchievementStatus')->save($as);
2064            array_push($updated, $achievementId);
2065        }
2066        $achievementId = 67;
2067        if ($currentElo >= 2300 && !isset($existingAs[$achievementId])) {
2068            $as['AchievementStatus']['achievement_id'] = $achievementId;
2069            ClassRegistry::init('AchievementStatus')->create();
2070            ClassRegistry::init('AchievementStatus')->save($as);
2071            array_push($updated, $achievementId);
2072        }
2073        $achievementId = 68;
2074        if ($currentElo >= 2400 && !isset($existingAs[$achievementId])) {
2075            $as['AchievementStatus']['achievement_id'] = $achievementId;
2076            ClassRegistry::init('AchievementStatus')->create();
2077            ClassRegistry::init('AchievementStatus')->save($as);
2078            array_push($updated, $achievementId);
2079        }
2080        $achievementId = 69;
2081        if ($currentElo >= 2500 && !isset($existingAs[$achievementId])) {
2082            $as['AchievementStatus']['achievement_id'] = $achievementId;
2083            ClassRegistry::init('AchievementStatus')->create();
2084            ClassRegistry::init('AchievementStatus')->save($as);
2085            array_push($updated, $achievementId);
2086        }
2087        $updatedCount = count($updated);
2088        for ($i = 0; $i < $updatedCount; $i++) {
2089            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2090            $updated[$i] = [];
2091            $updated[$i][0] = $a['Achievement']['name'];
2092            $updated[$i][1] = $a['Achievement']['description'];
2093            $updated[$i][2] = $a['Achievement']['image'];
2094            $updated[$i][3] = $a['Achievement']['color'];
2095            $updated[$i][4] = $a['Achievement']['xp'];
2096            $updated[$i][5] = $a['Achievement']['id'];
2097        }
2098
2099        return $updated;
2100    }
2101
2102    public static function checkLevelAchievements() {
2103        if (!Auth::isLoggedIn()) {
2104            return;
2105        }
2106        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2107        if (!$buffer) {
2108            $buffer = [];
2109        }
2110        $existingAs = [];
2111        $bufferCount = count($buffer);
2112        for ($i = 0; $i < $bufferCount; $i++) {
2113            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2114        }
2115        $as = [];
2116        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2117        $updated = [];
2118
2119        $achievementId = 36;
2120        $userLevel = Auth::getUser()['level'];
2121        if ($userLevel >= 10 && !isset($existingAs[$achievementId])) {
2122            $as['AchievementStatus']['achievement_id'] = $achievementId;
2123            ClassRegistry::init('AchievementStatus')->create();
2124            ClassRegistry::init('AchievementStatus')->save($as);
2125            array_push($updated, $achievementId);
2126        }
2127        $achievementId = 37;
2128        if ($userLevel >= 20 && !isset($existingAs[$achievementId])) {
2129            $as['AchievementStatus']['achievement_id'] = $achievementId;
2130            ClassRegistry::init('AchievementStatus')->create();
2131            ClassRegistry::init('AchievementStatus')->save($as);
2132            array_push($updated, $achievementId);
2133        }
2134        $achievementId = 38;
2135        if ($userLevel >= 30 && !isset($existingAs[$achievementId])) {
2136            $as['AchievementStatus']['achievement_id'] = $achievementId;
2137            ClassRegistry::init('AchievementStatus')->create();
2138            ClassRegistry::init('AchievementStatus')->save($as);
2139            array_push($updated, $achievementId);
2140        }
2141        $achievementId = 39;
2142        if ($userLevel >= 40 && !isset($existingAs[$achievementId])) {
2143            $as['AchievementStatus']['achievement_id'] = $achievementId;
2144            ClassRegistry::init('AchievementStatus')->create();
2145            ClassRegistry::init('AchievementStatus')->save($as);
2146            array_push($updated, $achievementId);
2147        }
2148        $achievementId = 40;
2149        if ($userLevel >= 50 && !isset($existingAs[$achievementId])) {
2150            $as['AchievementStatus']['achievement_id'] = $achievementId;
2151            ClassRegistry::init('AchievementStatus')->create();
2152            ClassRegistry::init('AchievementStatus')->save($as);
2153            array_push($updated, $achievementId);
2154        }
2155        $achievementId = 41;
2156        if ($userLevel >= 60 && !isset($existingAs[$achievementId])) {
2157            $as['AchievementStatus']['achievement_id'] = $achievementId;
2158            ClassRegistry::init('AchievementStatus')->create();
2159            ClassRegistry::init('AchievementStatus')->save($as);
2160            array_push($updated, $achievementId);
2161        }
2162        $achievementId = 42;
2163        if ($userLevel >= 70 && !isset($existingAs[$achievementId])) {
2164            $as['AchievementStatus']['achievement_id'] = $achievementId;
2165            ClassRegistry::init('AchievementStatus')->create();
2166            ClassRegistry::init('AchievementStatus')->save($as);
2167            array_push($updated, $achievementId);
2168        }
2169        $achievementId = 43;
2170        if ($userLevel >= 80 && !isset($existingAs[$achievementId])) {
2171            $as['AchievementStatus']['achievement_id'] = $achievementId;
2172            ClassRegistry::init('AchievementStatus')->create();
2173            ClassRegistry::init('AchievementStatus')->save($as);
2174            array_push($updated, $achievementId);
2175        }
2176        $achievementId = 44;
2177        if ($userLevel >= 90 && !isset($existingAs[$achievementId])) {
2178            $as['AchievementStatus']['achievement_id'] = $achievementId;
2179            ClassRegistry::init('AchievementStatus')->create();
2180            ClassRegistry::init('AchievementStatus')->save($as);
2181            array_push($updated, $achievementId);
2182        }
2183        $achievementId = 45;
2184        if ($userLevel >= 100 && !isset($existingAs[$achievementId])) {
2185            $as['AchievementStatus']['achievement_id'] = $achievementId;
2186            ClassRegistry::init('AchievementStatus')->create();
2187            ClassRegistry::init('AchievementStatus')->save($as);
2188            array_push($updated, $achievementId);
2189        }
2190        $achievementId = 100;
2191        if (Auth::hasPremium() && !isset($existingAs[$achievementId])) {
2192            $as['AchievementStatus']['achievement_id'] = $achievementId;
2193            ClassRegistry::init('AchievementStatus')->create();
2194            ClassRegistry::init('AchievementStatus')->save($as);
2195            array_push($updated, $achievementId);
2196        }
2197        $updatedCount = count($updated);
2198        for ($i = 0; $i < $updatedCount; $i++) {
2199            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2200            $updated[$i] = [];
2201            $updated[$i][0] = $a['Achievement']['name'];
2202            $updated[$i][1] = $a['Achievement']['description'];
2203            $updated[$i][2] = $a['Achievement']['image'];
2204            $updated[$i][3] = $a['Achievement']['color'];
2205            $updated[$i][4] = $a['Achievement']['xp'];
2206            $updated[$i][5] = $a['Achievement']['id'];
2207        }
2208
2209        return $updated;
2210    }
2211
2212    protected function checkSetCompletedAchievements() {
2213        $this->loadModel('Set');
2214        $this->loadModel('Tsumego');
2215        $this->loadModel('Achievement');
2216        $this->loadModel('AchievementStatus');
2217        $this->loadModel('AchievementCondition');
2218
2219        $ac = ClassRegistry::init('AchievementCondition')->find('first', [
2220            'order' => 'value DESC',
2221            'conditions' => [
2222                'user_id' => Auth::getUserID(),
2223                'category' => 'set',
2224            ],
2225        ]);
2226
2227        if (!$ac) {
2228            return [];
2229        }
2230
2231        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2232        if (!$buffer) {
2233            $buffer = [];
2234        }
2235        $existingAs = [];
2236        $bufferCount = count($buffer);
2237        for ($i = 0; $i < $bufferCount; $i++) {
2238            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2239        }
2240        $as = [];
2241        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2242        $updated = [];
2243
2244        $achievementId = 47;
2245        if ($ac['AchievementCondition']['value'] >= 10 && !isset($existingAs[$achievementId])) {
2246            $as['AchievementStatus']['achievement_id'] = $achievementId;
2247            ClassRegistry::init('AchievementStatus')->create();
2248            ClassRegistry::init('AchievementStatus')->save($as);
2249            array_push($updated, $achievementId);
2250        }
2251        $achievementId = 48;
2252        if ($ac['AchievementCondition']['value'] >= 20 && !isset($existingAs[$achievementId])) {
2253            $as['AchievementStatus']['achievement_id'] = $achievementId;
2254            ClassRegistry::init('AchievementStatus')->create();
2255            ClassRegistry::init('AchievementStatus')->save($as);
2256            array_push($updated, $achievementId);
2257        }
2258        $achievementId = 49;
2259        if ($ac['AchievementCondition']['value'] >= 30 && !isset($existingAs[$achievementId])) {
2260            $as['AchievementStatus']['achievement_id'] = $achievementId;
2261            ClassRegistry::init('AchievementStatus')->create();
2262            ClassRegistry::init('AchievementStatus')->save($as);
2263            array_push($updated, $achievementId);
2264        }
2265        $achievementId = 50;
2266        if ($ac['AchievementCondition']['value'] >= 40 && !isset($existingAs[$achievementId])) {
2267            $as['AchievementStatus']['achievement_id'] = $achievementId;
2268            ClassRegistry::init('AchievementStatus')->create();
2269            ClassRegistry::init('AchievementStatus')->save($as);
2270            array_push($updated, $achievementId);
2271        }
2272        $achievementId = 51;
2273        if ($ac['AchievementCondition']['value'] >= 50 && !isset($existingAs[$achievementId])) {
2274            $as['AchievementStatus']['achievement_id'] = $achievementId;
2275            ClassRegistry::init('AchievementStatus')->create();
2276            ClassRegistry::init('AchievementStatus')->save($as);
2277            array_push($updated, $achievementId);
2278        }
2279        $achievementId = 52;
2280        if ($ac['AchievementCondition']['value'] >= 60 && !isset($existingAs[$achievementId])) {
2281            $as['AchievementStatus']['achievement_id'] = $achievementId;
2282            ClassRegistry::init('AchievementStatus')->create();
2283            ClassRegistry::init('AchievementStatus')->save($as);
2284            array_push($updated, $achievementId);
2285        }
2286        $updatedCount = count($updated);
2287        for ($i = 0; $i < $updatedCount; $i++) {
2288            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2289            $updated[$i] = [];
2290            $updated[$i][0] = $a['Achievement']['name'];
2291            $updated[$i][1] = $a['Achievement']['description'];
2292            $updated[$i][2] = $a['Achievement']['image'];
2293            $updated[$i][3] = $a['Achievement']['color'];
2294            $updated[$i][4] = $a['Achievement']['xp'];
2295            $updated[$i][5] = $a['Achievement']['id'];
2296        }
2297
2298        return $updated;
2299    }
2300
2301    protected function setAchievementSpecial($s = null) {
2302        $this->loadModel('Set');
2303        $this->loadModel('Tsumego');
2304        $this->loadModel('TsumegoStatus');
2305        $this->loadModel('Achievement');
2306        $this->loadModel('AchievementStatus');
2307        $this->loadModel('SetConnection');
2308
2309        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2310        if (!$buffer) {
2311            $buffer = [];
2312        }
2313        $existingAs = [];
2314        $bufferCount = count($buffer);
2315        for ($i = 0; $i < $bufferCount; $i++) {
2316            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2317        }
2318        $as = [];
2319        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2320        $updated = [];
2321
2322        $tsIds = [];
2323        $completed = '';
2324        if ($s == 'cc1') {
2325            $ts1 = TsumegoUtil::collectTsumegosFromSet(50);
2326            $ts2 = TsumegoUtil::collectTsumegosFromSet(52);
2327            $ts3 = TsumegoUtil::collectTsumegosFromSet(53);
2328            $ts4 = TsumegoUtil::collectTsumegosFromSet(54);
2329            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2330            $tsCount = count($ts);
2331            for ($i = 0; $i < $tsCount; $i++) {
2332                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2333            }
2334            $uts = $this->TsumegoStatus->find('all', [
2335                'conditions' => [
2336                    'user_id' => Auth::getUserID(),
2337                    'tsumego_id' => $tsIds,
2338                ],
2339            ]);
2340            if (!$uts) {
2341                $uts = [];
2342            }
2343            $counter = 0;
2344            $utsCount = count($uts);
2345            for ($j = 0; $j < $utsCount; $j++) {
2346                for ($k = 0; $k < $tsCount; $k++) {
2347                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2348                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2349                        $counter++;
2350                    }
2351                }
2352            }
2353            if ($counter == count($ts)) {
2354                $completed = $s;
2355            }
2356        } elseif ($s == 'cc2') {
2357            $ts1 = TsumegoUtil::collectTsumegosFromSet(41);
2358            $ts2 = TsumegoUtil::collectTsumegosFromSet(49);
2359            $ts3 = TsumegoUtil::collectTsumegosFromSet(65);
2360            $ts4 = TsumegoUtil::collectTsumegosFromSet(66);
2361            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2362            $tsCount = count($ts);
2363            for ($i = 0; $i < $tsCount; $i++) {
2364                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2365            }
2366            $uts = $this->TsumegoStatus->find('all', [
2367                'conditions' => [
2368                    'user_id' => Auth::getUserID(),
2369                    'tsumego_id' => $tsIds,
2370                ],
2371            ]);
2372            if (!$uts) {
2373                $uts = [];
2374            }
2375            $counter = 0;
2376            $utsCount = count($uts);
2377            for ($j = 0; $j < $utsCount; $j++) {
2378                for ($k = 0; $k < $tsCount; $k++) {
2379                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2380                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2381                        $counter++;
2382                    }
2383                }
2384            }
2385            if ($counter == count($ts)) {
2386                $completed = $s;
2387            }
2388        } elseif ($s == 'cc3') {
2389            $ts1 = TsumegoUtil::collectTsumegosFromSet(186);
2390            $ts2 = TsumegoUtil::collectTsumegosFromSet(187);
2391            $ts3 = TsumegoUtil::collectTsumegosFromSet(196);
2392            $ts4 = TsumegoUtil::collectTsumegosFromSet(203);
2393            $ts = array_merge($ts1, $ts2, $ts3, $ts4);
2394            $tsCount = count($ts);
2395            for ($i = 0; $i < $tsCount; $i++) {
2396                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2397            }
2398            $uts = $this->TsumegoStatus->find('all', [
2399                'conditions' => [
2400                    'user_id' => Auth::getUserID(),
2401                    'tsumego_id' => $tsIds,
2402                ],
2403            ]);
2404            if (!$uts) {
2405                $uts = [];
2406            }
2407            $counter = 0;
2408            $utsCount = count($uts);
2409            for ($j = 0; $j < $utsCount; $j++) {
2410                for ($k = 0; $k < $tsCount; $k++) {
2411                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2412                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2413                        $counter++;
2414                    }
2415                }
2416            }
2417            if ($counter == count($ts)) {
2418                $completed = $s;
2419            }
2420        } elseif ($s == '1000w1') {
2421            $ts1 = TsumegoUtil::collectTsumegosFromSet(190);
2422            $ts2 = TsumegoUtil::collectTsumegosFromSet(193);
2423            $ts3 = TsumegoUtil::collectTsumegosFromSet(198);
2424            $ts = array_merge($ts1, $ts2, $ts3);
2425            $tsCount = count($ts);
2426            for ($i = 0; $i < $tsCount; $i++) {
2427                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2428            }
2429            $uts = $this->TsumegoStatus->find('all', [
2430                'conditions' => [
2431                    'user_id' => Auth::getUserID(),
2432                    'tsumego_id' => $tsIds,
2433                ],
2434            ]);
2435            if (!$uts) {
2436                $uts = [];
2437            }
2438            $counter = 0;
2439            $utsCount = count($uts);
2440            for ($j = 0; $j < $utsCount; $j++) {
2441                for ($k = 0; $k < $tsCount; $k++) {
2442                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2443                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2444                        $counter++;
2445                    }
2446                }
2447            }
2448            if ($counter == count($ts)) {
2449                $completed = $s;
2450            }
2451        } elseif ($s == '1000w2') {
2452            $ts = TsumegoUtil::collectTsumegosFromSet(216);
2453            $tsCount = count($ts);
2454            for ($i = 0; $i < $tsCount; $i++) {
2455                array_push($tsIds, $ts[$i]['Tsumego']['id']);
2456            }
2457            $uts = $this->TsumegoStatus->find('all', [
2458                'conditions' => [
2459                    'user_id' => Auth::getUserID(),
2460                    'tsumego_id' => $tsIds,
2461                ],
2462            ]);
2463            if (!$uts) {
2464                $uts = [];
2465            }
2466            $counter = 0;
2467            $utsCount = count($uts);
2468            for ($j = 0; $j < $utsCount; $j++) {
2469                for ($k = 0; $k < $tsCount; $k++) {
2470                    if ($uts[$j]['TsumegoStatus']['tsumego_id'] == $ts[$k]['Tsumego']['id'] && ($uts[$j]['TsumegoStatus']['status'] == 'S'
2471                    || $uts[$j]['TsumegoStatus']['status'] == 'W' || $uts[$j]['TsumegoStatus']['status'] == 'C')) {
2472                        $counter++;
2473                    }
2474                }
2475            }
2476            if ($counter == count($ts)) {
2477                $completed = $s;
2478            }
2479        }
2480
2481        $achievementId = 92;
2482        if ($completed == 'cc1' && !isset($existingAs[$achievementId])) {
2483            $as['AchievementStatus']['achievement_id'] = $achievementId;
2484            ClassRegistry::init('AchievementStatus')->create();
2485            ClassRegistry::init('AchievementStatus')->save($as);
2486            array_push($updated, $achievementId);
2487        }
2488        $achievementId = 93;
2489        if ($completed == 'cc2' && !isset($existingAs[$achievementId])) {
2490            $as['AchievementStatus']['achievement_id'] = $achievementId;
2491            ClassRegistry::init('AchievementStatus')->create();
2492            ClassRegistry::init('AchievementStatus')->save($as);
2493            array_push($updated, $achievementId);
2494        }
2495        $achievementId = 94;
2496        if ($completed == 'cc3' && !isset($existingAs[$achievementId])) {
2497            $as['AchievementStatus']['achievement_id'] = $achievementId;
2498            ClassRegistry::init('AchievementStatus')->create();
2499            ClassRegistry::init('AchievementStatus')->save($as);
2500            array_push($updated, $achievementId);
2501        }
2502        $achievementId = 95;
2503        if ($completed == '1000w1' && !isset($existingAs[$achievementId])) {
2504            $as['AchievementStatus']['achievement_id'] = $achievementId;
2505            ClassRegistry::init('AchievementStatus')->create();
2506            ClassRegistry::init('AchievementStatus')->save($as);
2507            array_push($updated, $achievementId);
2508        }
2509        $achievementId = 115;
2510        if ($completed == '1000w2' && !isset($existingAs[$achievementId])) {
2511            $as['AchievementStatus']['achievement_id'] = $achievementId;
2512            ClassRegistry::init('AchievementStatus')->create();
2513            ClassRegistry::init('AchievementStatus')->save($as);
2514            array_push($updated, $achievementId);
2515        }
2516        $updatedCount = count($updated);
2517        for ($i = 0; $i < $updatedCount; $i++) {
2518            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2519            $updated[$i] = [];
2520            $updated[$i][0] = $a['Achievement']['name'];
2521            $updated[$i][1] = $a['Achievement']['description'];
2522            $updated[$i][2] = $a['Achievement']['image'];
2523            $updated[$i][3] = $a['Achievement']['color'];
2524            $updated[$i][4] = $a['Achievement']['xp'];
2525            $updated[$i][5] = $a['Achievement']['id'];
2526        }
2527
2528        return $updated;
2529    }
2530
2531    protected function checkSetAchievements($sid = null) {
2532        $this->loadModel('Set');
2533        $this->loadModel('Tsumego');
2534        $this->loadModel('Achievement');
2535        $this->loadModel('AchievementStatus');
2536        $this->loadModel('AchievementCondition');
2537
2538        //$tNum = count($this->Tsumego->find('all', array('conditions' => array('set_id' => $sid))));
2539        $tNum = count(TsumegoUtil::collectTsumegosFromSet($sid));
2540        $s = $this->Set->findById($sid);
2541        $acA = ClassRegistry::init('AchievementCondition')->find('first', [
2542            'order' => 'value DESC',
2543            'conditions' => [
2544                'set_id' => $sid,
2545                'user_id' => Auth::getUserID(),
2546                'category' => '%',
2547            ],
2548        ]);
2549        if (!$acA) {
2550            return [];
2551        }
2552        $acS = ClassRegistry::init('AchievementCondition')->find('first', [
2553            'order' => 'value ASC',
2554            'conditions' => [
2555                'set_id' => $sid,
2556                'user_id' => Auth::getUserID(),
2557                'category' => 's',
2558            ],
2559        ]);
2560        $buffer = ClassRegistry::init('AchievementStatus')->find('all', ['conditions' => ['user_id' => Auth::getUserID()]]);
2561        if (!$buffer) {
2562            $buffer = [];
2563        }
2564        $existingAs = [];
2565        $bufferCount = count($buffer);
2566        for ($i = 0; $i < $bufferCount; $i++) {
2567            $existingAs[$buffer[$i]['AchievementStatus']['achievement_id']] = $buffer[$i];
2568        }
2569        $as = [];
2570        $as['AchievementStatus']['user_id'] = Auth::getUserID();
2571        $updated = [];
2572
2573        $achievementId = 99;
2574        if ($sid == -1 && !isset($existingAs[$achievementId])) {
2575            $as['AchievementStatus']['achievement_id'] = $achievementId;
2576            ClassRegistry::init('AchievementStatus')->create();
2577            ClassRegistry::init('AchievementStatus')->save($as);
2578            array_push($updated, $achievementId);
2579        }
2580        if ($tNum >= 100) {
2581            if ($s['Set']['difficulty'] < 1300) {
2582                $achievementId = 12;
2583                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2584                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2585                    ClassRegistry::init('AchievementStatus')->create();
2586                    ClassRegistry::init('AchievementStatus')->save($as);
2587                    array_push($updated, $achievementId);
2588                }
2589                $achievementId = 13;
2590                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2591                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2592                    ClassRegistry::init('AchievementStatus')->create();
2593                    ClassRegistry::init('AchievementStatus')->save($as);
2594                    array_push($updated, $achievementId);
2595                }
2596                $achievementId = 14;
2597                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2598                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2599                    ClassRegistry::init('AchievementStatus')->create();
2600                    ClassRegistry::init('AchievementStatus')->save($as);
2601                    array_push($updated, $achievementId);
2602                }
2603                $achievementId = 24;
2604                if ($acS['AchievementCondition']['value'] < 15 && !isset($existingAs[$achievementId])) {
2605                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2606                    ClassRegistry::init('AchievementStatus')->create();
2607                    ClassRegistry::init('AchievementStatus')->save($as);
2608                    array_push($updated, $achievementId);
2609                }
2610                $achievementId = 25;
2611                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2612                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2613                    ClassRegistry::init('AchievementStatus')->create();
2614                    ClassRegistry::init('AchievementStatus')->save($as);
2615                    array_push($updated, $achievementId);
2616                }
2617                $achievementId = 26;
2618                if ($acS['AchievementCondition']['value'] < 5 && !isset($existingAs[$achievementId])) {
2619                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2620                    ClassRegistry::init('AchievementStatus')->create();
2621                    ClassRegistry::init('AchievementStatus')->save($as);
2622                    array_push($updated, $achievementId);
2623                }
2624            } elseif ($s['Set']['difficulty'] >= 1300 && $s['Set']['difficulty'] < 1500) {
2625                $achievementId = 15;
2626                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2627                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2628                    ClassRegistry::init('AchievementStatus')->create();
2629                    ClassRegistry::init('AchievementStatus')->save($as);
2630                    array_push($updated, $achievementId);
2631                }
2632                $achievementId = 16;
2633                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2634                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2635                    ClassRegistry::init('AchievementStatus')->create();
2636                    ClassRegistry::init('AchievementStatus')->save($as);
2637                    array_push($updated, $achievementId);
2638                }
2639                $achievementId = 17;
2640                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2641                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2642                    ClassRegistry::init('AchievementStatus')->create();
2643                    ClassRegistry::init('AchievementStatus')->save($as);
2644                    array_push($updated, $achievementId);
2645                }
2646                $achievementId = 27;
2647                if ($acS['AchievementCondition']['value'] < 18 && !isset($existingAs[$achievementId])) {
2648                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2649                    ClassRegistry::init('AchievementStatus')->create();
2650                    ClassRegistry::init('AchievementStatus')->save($as);
2651                    array_push($updated, $achievementId);
2652                }
2653                $achievementId = 28;
2654                if ($acS['AchievementCondition']['value'] < 13 && !isset($existingAs[$achievementId])) {
2655                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2656                    ClassRegistry::init('AchievementStatus')->create();
2657                    ClassRegistry::init('AchievementStatus')->save($as);
2658                    array_push($updated, $achievementId);
2659                }
2660                $achievementId = 29;
2661                if ($acS['AchievementCondition']['value'] < 8 && !isset($existingAs[$achievementId])) {
2662                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2663                    ClassRegistry::init('AchievementStatus')->create();
2664                    ClassRegistry::init('AchievementStatus')->save($as);
2665                    array_push($updated, $achievementId);
2666                }
2667            } elseif ($s['Set']['difficulty'] >= 1500 && $s['Set']['difficulty'] < 1700) {
2668                $achievementId = 18;
2669                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2670                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2671                    ClassRegistry::init('AchievementStatus')->create();
2672                    ClassRegistry::init('AchievementStatus')->save($as);
2673                    array_push($updated, $achievementId);
2674                }
2675                $achievementId = 19;
2676                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2677                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2678                    ClassRegistry::init('AchievementStatus')->create();
2679                    ClassRegistry::init('AchievementStatus')->save($as);
2680                    array_push($updated, $achievementId);
2681                }
2682                $achievementId = 20;
2683                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2684                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2685                    ClassRegistry::init('AchievementStatus')->create();
2686                    ClassRegistry::init('AchievementStatus')->save($as);
2687                    array_push($updated, $achievementId);
2688                }
2689                $achievementId = 30;
2690                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2691                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2692                    ClassRegistry::init('AchievementStatus')->create();
2693                    ClassRegistry::init('AchievementStatus')->save($as);
2694                    array_push($updated, $achievementId);
2695                }
2696                $achievementId = 31;
2697                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2698                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2699                    ClassRegistry::init('AchievementStatus')->create();
2700                    ClassRegistry::init('AchievementStatus')->save($as);
2701                    array_push($updated, $achievementId);
2702                }
2703                $achievementId = 32;
2704                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2705                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2706                    ClassRegistry::init('AchievementStatus')->create();
2707                    ClassRegistry::init('AchievementStatus')->save($as);
2708                    array_push($updated, $achievementId);
2709                }
2710            } else {
2711                $achievementId = 21;
2712                if ($acA['AchievementCondition']['value'] >= 75 && !isset($existingAs[$achievementId])) {
2713                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2714                    ClassRegistry::init('AchievementStatus')->create();
2715                    ClassRegistry::init('AchievementStatus')->save($as);
2716                    array_push($updated, $achievementId);
2717                }
2718                $achievementId = 22;
2719                if ($acA['AchievementCondition']['value'] >= 85 && !isset($existingAs[$achievementId])) {
2720                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2721                    ClassRegistry::init('AchievementStatus')->create();
2722                    ClassRegistry::init('AchievementStatus')->save($as);
2723                    array_push($updated, $achievementId);
2724                }
2725                $achievementId = 23;
2726                if ($acA['AchievementCondition']['value'] >= 95 && !isset($existingAs[$achievementId])) {
2727                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2728                    ClassRegistry::init('AchievementStatus')->create();
2729                    ClassRegistry::init('AchievementStatus')->save($as);
2730                    array_push($updated, $achievementId);
2731                }
2732                $achievementId = 33;
2733                if ($acS['AchievementCondition']['value'] < 30 && !isset($existingAs[$achievementId])) {
2734                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2735                    ClassRegistry::init('AchievementStatus')->create();
2736                    ClassRegistry::init('AchievementStatus')->save($as);
2737                    array_push($updated, $achievementId);
2738                }
2739                $achievementId = 34;
2740                if ($acS['AchievementCondition']['value'] < 20 && !isset($existingAs[$achievementId])) {
2741                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2742                    ClassRegistry::init('AchievementStatus')->create();
2743                    ClassRegistry::init('AchievementStatus')->save($as);
2744                    array_push($updated, $achievementId);
2745                }
2746                $achievementId = 35;
2747                if ($acS['AchievementCondition']['value'] < 10 && !isset($existingAs[$achievementId])) {
2748                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2749                    ClassRegistry::init('AchievementStatus')->create();
2750                    ClassRegistry::init('AchievementStatus')->save($as);
2751                    array_push($updated, $achievementId);
2752                }
2753            }
2754            $achievementId = 46;
2755            if ($acA['AchievementCondition']['value'] >= 100) {
2756                $ac100 = ClassRegistry::init('AchievementCondition')->find('all', ['conditions' => ['user_id' => Auth::getUserID(), 'category' => '%', 'value >=' => 100]]);
2757                if (!$ac100) {
2758                    $ac100 = [];
2759                }
2760                $ac100counter = 0;
2761                $ac100Count = count($ac100);
2762                for ($j = 0; $j < $ac100Count; $j++) {
2763                    if (count(TsumegoUtil::collectTsumegosFromSet($ac100[$j]['AchievementCondition']['set_id'])) >= 100) {
2764                        $ac100counter++;
2765                    }
2766                }
2767                $as100 = ClassRegistry::init('AchievementStatus')->find('first', ['conditions' => ['user_id' => Auth::getUserID(), 'achievement_id' => $achievementId]]);
2768                if ($as100 == null) {
2769                    $as['AchievementStatus']['achievement_id'] = $achievementId;
2770                    $as['AchievementStatus']['value'] = 1;
2771                    ClassRegistry::init('AchievementStatus')->create();
2772                    ClassRegistry::init('AchievementStatus')->save($as);
2773                    array_push($updated, $achievementId);
2774                } elseif ($as100['AchievementStatus']['value'] != $ac100counter) {
2775                    $as100['AchievementStatus']['value'] = $ac100counter;
2776                    ClassRegistry::init('AchievementStatus')->save($as100);
2777                    array_push($updated, $achievementId);
2778                }
2779            }
2780        }
2781        $updatedCount = count($updated);
2782        for ($i = 0; $i < $updatedCount; $i++) {
2783            $a = ClassRegistry::init('Achievement')->findById($updated[$i]);
2784            $updated[$i] = [];
2785            $updated[$i][0] = $a['Achievement']['name'];
2786            $updated[$i][1] = $a['Achievement']['description'];
2787            $updated[$i][2] = $a['Achievement']['image'];
2788            $updated[$i][3] = $a['Achievement']['color'];
2789            $updated[$i][4] = $a['Achievement']['xp'];
2790            $updated[$i][5] = $a['Achievement']['id'];
2791        }
2792
2793        return $updated;
2794    }
2795
2796    public static function getXPJump($lvl = null): int {
2797        if ($lvl >= 102) {
2798            return 0;
2799        }
2800        if ($lvl == 101) {
2801            return 1150;
2802        }
2803        if ($lvl == 100) {
2804            return 50000;
2805        }
2806        if ($lvl >= 70) {
2807            return 150;
2808        }
2809        if ($lvl >= 40) {
2810            return 100;
2811        }
2812        if ($lvl >= 20) {
2813            return 50;
2814        }
2815        if ($lvl >= 12) {
2816            return 25;
2817        }
2818
2819        return 10;
2820    }
2821
2822    public static function updateXP($userID, $achievementData): void {
2823        $xpBonus = 0;
2824        $aCount = count($achievementData);
2825        for ($i = 0; $i < $aCount; $i++) {
2826            $xpBonus += $achievementData[$i][4];
2827        }
2828        if ($xpBonus == 0) {
2829            return;
2830        }
2831        $user = ClassRegistry::init('User')->findById($userID);
2832        $user['User']['xp'] = $xpBonus;
2833        Level::checkLevelUp($user['User']);
2834        ClassRegistry::init('User')->save($user);
2835    }
2836
2837    public static function getPartitionRange($amountRemaining, $collectionSize, $partition) {
2838        if ($collectionSize > 0) {
2839            $amountPartitions = ceil($amountRemaining / $collectionSize);
2840        } else {
2841            return ['0', $collectionSize - 1];
2842        }
2843        if ($collectionSize > 0 && $amountRemaining % $collectionSize == 0) {
2844            return [ $partition * $collectionSize,  $partition * $collectionSize + $collectionSize - 1];
2845        }
2846        $amountCounter = 0;
2847        $amountFrom = 0;
2848        $amountTo = $collectionSize - 1;
2849        while ($amountRemaining > $collectionSize) {
2850            if ($partition == $amountCounter) {
2851                break;
2852            }
2853            $amountRemaining -= $collectionSize;
2854            $amountCounter++;
2855            $amountFrom += $collectionSize;
2856            $amountTo += $collectionSize;
2857        }
2858        $amountTo = $amountFrom + $collectionSize - 1;
2859        if ($partition >= $amountPartitions - 1) {
2860            $amountTo = $amountFrom + $amountRemaining - 1;
2861        }
2862        $a = [];
2863        $a[0] = $amountFrom;
2864        $a[1] = $amountTo;
2865
2866        return $a;
2867    }
2868
2869    /**
2870     * @param int $uid User ID
2871     * @return void
2872     */
2873    protected function handleSearchSettings($uid) {
2874        $this->loadModel('UserContribution');
2875        $uc = $this->UserContribution->find('first', ['conditions' => ['user_id' => $uid]]);
2876        if ($uc == null) {
2877            $uc = [];
2878            $uc['UserContribution']['user_id'] = $uid;
2879            $uc['UserContribution']['added_tag'] = 0;
2880            $uc['UserContribution']['created_tag'] = 0;
2881            $uc['UserContribution']['made_proposal'] = 0;
2882            $uc['UserContribution']['reviewed'] = 0;
2883            $uc['UserContribution']['score'] = 0;
2884            $this->UserContribution->create();
2885            $this->UserContribution->save($uc);
2886        }
2887        new TsumegoFilters();
2888    }
2889
2890    protected function signIn(array $user): void {
2891        Auth::init($user);
2892        $vs = $this->TsumegoStatus->find('first', ['conditions' => ['user_id' => $user['User']['id']], 'order' => 'updated DESC']);
2893        if ($vs) {
2894            $this->Session->write('lastVisit', $vs['TsumegoStatus']['tsumego_id']);
2895        }
2896        $this->Session->write('texture', $user['User']['texture']);
2897        $this->Session->write('check1', $user['User']['id']);
2898    }
2899
2900    public function beforeFilter(): void {
2901        $this->loadModel('User');
2902        $this->loadModel('Activate');
2903        $this->loadModel('Tsumego');
2904        $this->loadModel('TsumegoRatingAttempt');
2905        $this->loadModel('Set');
2906        $this->loadModel('TimeModeAttempt');
2907        $this->loadModel('TsumegoStatus');
2908        $this->loadModel('Comment');
2909        $this->loadModel('TsumegoAttempt');
2910        $this->loadModel('AdminActivity');
2911        $this->loadModel('Achievement');
2912        $this->loadModel('AchievementStatus');
2913        $this->loadModel('AchievementCondition');
2914        $this->loadModel('SetConnection');
2915        $this->loadModel('Tag');
2916        $this->loadModel('TagName');
2917        $this->loadModel('Favorite');
2918
2919        Auth::init();
2920        $timeMode = new TimeMode();
2921
2922        $highscoreLink = 'highscore';
2923        $lightDark = 'light';
2924        $resetCookies = false;
2925        $levelBar = 1;
2926        $lastProfileLeft = 1;
2927        $lastProfileRight = 2;
2928        $hasFavs = false;
2929
2930        if (Auth::isLoggedIn()) {
2931            if (isset($_COOKIE['addTag']) && $_COOKIE['addTag'] != 0 && $this->Session->read('page') != 'set') {
2932                $newAddTag = explode('-', $_COOKIE['addTag']);
2933                $tagId = $newAddTag[0];
2934                $newTagName = $this->TagName->find('first', ['conditions' => ['name' => str_replace($tagId . '-', '', $_COOKIE['addTag'])]]);
2935                if ($newTagName) {
2936                    $saveTag = [];
2937                    $saveTag['Tag']['tag_name_id'] = $newTagName['TagName']['id'];
2938                    $saveTag['Tag']['tsumego_id'] = $tagId;
2939                    $saveTag['Tag']['user_id'] = Auth::getUserID();
2940                    $saveTag['Tag']['approved'] = 0;
2941                    $this->Tag->save($saveTag);
2942                }
2943                $this->set('removeCookie', 'addTag');
2944            }
2945            if (isset($_COOKIE['z_sess']) && $_COOKIE['z_sess'] != 0
2946            && strlen($_COOKIE['z_sess']) > 5) {
2947                Auth::getUser()['_sessid'] = $_COOKIE['z_sess'];
2948                Auth::saveUser();
2949            }
2950            if (Auth::getUser()['lastHighscore'] == 1) {
2951                $highscoreLink = 'highscore';
2952            } elseif (Auth::getUser()['lastHighscore'] == 2) {
2953                $highscoreLink = 'rating';
2954            } elseif (Auth::getUser()['lastHighscore'] == 3) {
2955                $highscoreLink = 'leaderboard';
2956            } elseif (Auth::getUser()['lastHighscore'] == 4) {
2957                $highscoreLink = 'highscore3';
2958            }
2959
2960            if (isset($_COOKIE['lastMode']) && $_COOKIE['lastMode'] != 0) {
2961                Auth::getUser()['lastMode'] = $_COOKIE['lastMode'];
2962                Auth::saveUser();
2963            }
2964            if (isset($_COOKIE['sound']) && $_COOKIE['sound'] != '0') {
2965                Auth::getUser()['sound'] = $_COOKIE['sound'];
2966                Auth::saveUser();
2967                unset($_COOKIE['sound']);
2968            }
2969            $this->set('ac', true);
2970            $this->set('user', Auth::getUser());
2971        }
2972
2973        if (isset($_COOKIE['lightDark']) && $_COOKIE['lightDark'] != '0') {
2974            $lightDark = $_COOKIE['lightDark'];
2975            if (Auth::isLoggedIn()) {
2976                // Convert string to integer for database storage
2977                $lightDarkInt = ($lightDark === 'light') ? 0 : 2;
2978                Auth::getUser()['lastLight'] = $lightDarkInt;
2979            }
2980        } elseif (Auth::isLoggedIn()) {
2981            if (Auth::getUser()['lastLight'] == 0
2982            || Auth::getUser()['lastLight'] == 1) {
2983                $lightDark = 'light';
2984            } else {
2985                $lightDark = 'dark';
2986            }
2987        }
2988
2989        if (Auth::isLoggedIn()) {
2990            $this->handleSearchSettings(Auth::getUserID());
2991            if (isset($_COOKIE['levelBar']) && $_COOKIE['levelBar'] != '0') {
2992                $levelBar = $_COOKIE['levelBar'];
2993                Auth::getUser()['levelBar'] = $levelBar;
2994            } elseif (Auth::getUser()['levelBar'] == 0
2995          || Auth::getUser()['levelBar'] == 'level') {
2996                $levelBar = 1;
2997            } else {
2998                $levelBar = 2;
2999            }
3000
3001            if (isset($_COOKIE['lastProfileLeft']) && $_COOKIE['lastProfileLeft'] != '0') {
3002                $lastProfileLeft = $_COOKIE['lastProfileLeft'];
3003                Auth::getUser()['lastProfileLeft'] = $lastProfileLeft;
3004            } else {
3005                $lastProfileLeft = Auth::getUser()['lastProfileLeft'];
3006                if ($lastProfileLeft == 0) {
3007                    $lastProfileLeft = 1;
3008                }
3009            }
3010            if (isset($_COOKIE['lastProfileRight']) && $_COOKIE['lastProfileRight'] != '0') {
3011                $lastProfileRight = $_COOKIE['lastProfileRight'];
3012                Auth::getUser()['lastProfileRight'] = $lastProfileRight;
3013            } else {
3014                $lastProfileRight = Auth::getUser()['lastProfileRight'];
3015                if ($lastProfileRight == 0) {
3016                    $lastProfileRight = 1;
3017                }
3018            }
3019        }
3020        $mode = 1;
3021        if (isset($_COOKIE['mode']) && $_COOKIE['mode'] != '0') {
3022            if ($_COOKIE['mode'] == 1) {
3023                $mode = 1;
3024            } else {
3025                $mode = 2;
3026            }
3027        }
3028
3029        if (Auth::isLoggedIn() && Auth::getUser()['mode'] == 2) {
3030            $mode = 2;
3031        }
3032
3033        if ($_COOKIE['sprint'] != 1) {
3034            $this->updateSprintCondition();
3035        }
3036        $correctSolveAttempt = false;
3037
3038        if (Auth::isLoggedIn()) {
3039            if (isset($_COOKIE['revelation']) && $_COOKIE['revelation'] != 0) {
3040                Auth::getUser()['revelation'] -= 1;
3041            }
3042
3043            if (!$this->request->is('ajax')) {
3044                $this->PlayResultProcessor->checkPreviousPlay($timeMode);
3045            }
3046
3047            if (isset($_COOKIE['noScore']) && isset($_COOKIE['noPreId'])) {
3048                if ($_COOKIE['noScore'] != '0' && $_COOKIE['noPreId'] != '0') {
3049                    //$previosTsumegoX = $this->Tsumego->findById($_COOKIE['noPreId']);
3050                    //$previosTsumegoXsc = $this->SetConnection->find('first', array('conditions' => array('tsumego_id' => $_COOKIE['noPreId'])));
3051                    //$scoreArrX = explode('-', $this->decrypt($_COOKIE['noScore']));
3052
3053                    $utPreX = $this->TsumegoStatus->find('first', ['conditions' => ['tsumego_id' => $_COOKIE['noPreId'], 'user_id' => Auth::getUserID()]]);
3054                    if ($utPreX == null) {
3055                        $utPreX['TsumegoStatus'] = [];
3056                        $utPreX['TsumegoStatus']['user_id'] = Auth::getUserID();
3057                        $utPreX['TsumegoStatus']['tsumego_id'] = $_COOKIE['noPreId'];
3058                    }
3059                    if ($utPreX['TsumegoStatus']['status'] == 'W') {
3060                        $utPreX['TsumegoStatus']['status'] = 'C';
3061                    } else {
3062                        $utPreX['TsumegoStatus']['status'] = 'S';
3063                    }
3064                    $utPreX['TsumegoStatus']['created'] = date('Y-m-d H:i:s');
3065                    //$this->TsumegoStatus->save($utPreX);
3066                    //$sessionUts = $this->Session->read('loggedInUser.uts');
3067                    /*if (!$sessionUts) {
3068                    $sessionUts = [];
3069                    }
3070                    $sessionUts[$utPreX['TsumegoStatus']['tsumego_id']] = $utPreX['TsumegoStatus']['status'];
3071                    $this->Session->write('loggedInUser.uts', $sessionUts);*/
3072                }
3073            }
3074        }
3075        $boardNames = [];
3076        $enabledBoards = [];
3077        $boardPositions = [];
3078
3079        $boardNames[1] = 'Pine';
3080        $boardNames[2] = 'Ash';
3081        $boardNames[3] = 'Maple';
3082        $boardNames[4] = 'Shin Kaya';
3083        $boardNames[5] = 'Birch';
3084        $boardNames[6] = 'Wenge';
3085        $boardNames[7] = 'Walnut';
3086        $boardNames[8] = 'Mahogany';
3087        $boardNames[9] = 'Blackwood';
3088        $boardNames[10] = 'Marble 1';
3089        $boardNames[11] = 'Marble 2';
3090        $boardNames[12] = 'Marble 3';
3091        $boardNames[13] = 'Tibet Spruce';
3092        $boardNames[14] = 'Marble 4';
3093        $boardNames[15] = 'Marble 5';
3094        $boardNames[16] = 'Quarry 1';
3095        $boardNames[17] = 'Flowers';
3096        $boardNames[18] = 'Nova';
3097        $boardNames[19] = 'Spring';
3098        $boardNames[20] = 'Moon';
3099        $boardNames[21] = 'Apex';
3100        $boardNames[22] = 'Gold 1';
3101        $boardNames[23] = 'Amber';
3102        $boardNames[24] = 'Marble 6';
3103        $boardNames[25] = 'Marble 7';
3104        $boardNames[26] = 'Marble 8';
3105        $boardNames[27] = 'Marble 9';
3106        $boardNames[28] = 'Marble 10';
3107        $boardNames[29] = 'Jade';
3108        $boardNames[30] = 'Quarry 2';
3109        $boardNames[31] = 'Black Bricks';
3110        $boardNames[32] = 'Wallpaper 1';
3111        $boardNames[33] = 'Wallpaper 2';
3112        $boardNames[34] = 'Gold & Gray';
3113        $boardNames[35] = 'Gold & Pink';
3114        $boardNames[36] = 'Veil';
3115        $boardNames[37] = 'Tiles';
3116        $boardNames[38] = 'Mars';
3117        $boardNames[39] = 'Pink Cloud';
3118        $boardNames[40] = 'Reptile';
3119        $boardNames[41] = 'Mezmerizing';
3120        $boardNames[42] = 'Magenta Sky';
3121        $boardNames[43] = 'Tsumego Hero';
3122        $boardNames[44] = 'Pretty';
3123        $boardNames[45] = 'Hunting';
3124        $boardNames[46] = 'Haunted';
3125        $boardNames[47] = 'Carnage';
3126        $boardNames[48] = 'Blind Spot';
3127        $boardNames[49] = 'Giants';
3128        $boardNames[50] = 'Gems';
3129        $boardNames[51] = 'Grandmaster';
3130        $boardPositions[1] = [1, 'texture1', 'black34.png', 'white34.png'];
3131        $boardPositions[2] = [2, 'texture2', 'black34.png', 'white34.png'];
3132        $boardPositions[3] = [3, 'texture3', 'black34.png', 'white34.png'];
3133        $boardPositions[4] = [4, 'texture4', 'black.png', 'white.png'];
3134        $boardPositions[5] = [5, 'texture5', 'black34.png', 'white34.png'];
3135        $boardPositions[6] = [6, 'texture6', 'black.png', 'white.png'];
3136        $boardPositions[7] = [7, 'texture7', 'black34.png', 'white34.png'];
3137        $boardPositions[8] = [8, 'texture8', 'black.png', 'white.png'];
3138        $boardPositions[9] = [9, 'texture9', 'black.png', 'white.png'];
3139        $boardPositions[10] = [10, 'texture10', 'black34.png', 'white34.png'];
3140        $boardPositions[11] = [11, 'texture11', 'black34.png', 'white34.png'];
3141        $boardPositions[12] = [12, 'texture12', 'black34.png', 'white34.png'];
3142        $boardPositions[13] = [13, 'texture13', 'black34.png', 'white34.png'];
3143        $boardPositions[14] = [14, 'texture14', 'black34.png', 'white34.png'];
3144        $boardPositions[15] = [15, 'texture15', 'black.png', 'white.png'];
3145        $boardPositions[16] = [16, 'texture16', 'black34.png', 'white34.png'];
3146        $boardPositions[17] = [17, 'texture17', 'black34.png', 'white34.png'];
3147        $boardPositions[18] = [18, 'texture18', 'black.png', 'white.png'];
3148        $boardPositions[19] = [19, 'texture19', 'black34.png', 'white34.png'];
3149        $boardPositions[20] = [20, 'texture20', 'black34.png', 'white34.png'];
3150        $boardPositions[21] = [33, 'texture33', 'black34.png', 'white34.png'];
3151        $boardPositions[22] = [21, 'texture21', 'black.png', 'whiteKo.png'];
3152        $boardPositions[23] = [22, 'texture22', 'black34.png', 'white34.png'];
3153        $boardPositions[24] = [34, 'texture34', 'black.png', 'white.png'];
3154        $boardPositions[25] = [35, 'texture35', 'black34.png', 'white34.png'];
3155        $boardPositions[26] = [36, 'texture36', 'black.png', 'white.png'];
3156        $boardPositions[27] = [37, 'texture37', 'black34.png', 'white34.png'];
3157        $boardPositions[28] = [38, 'texture38', 'black38.png', 'white34.png'];
3158        $boardPositions[29] = [39, 'texture39', 'black.png', 'white.png'];
3159        $boardPositions[30] = [40, 'texture40', 'black34.png', 'white34.png'];
3160        $boardPositions[31] = [41, 'texture41', 'black34.png', 'white34.png'];
3161        $boardPositions[32] = [42, 'texture42', 'black34.png', 'white42.png'];
3162        $boardPositions[33] = [43, 'texture43', 'black34.png', 'white42.png'];
3163        $boardPositions[34] = [44, 'texture44', 'black34.png', 'white34.png'];
3164        $boardPositions[35] = [45, 'texture45', 'black34.png', 'white42.png'];
3165        $boardPositions[36] = [47, 'texture47', 'black34.png', 'white34.png'];
3166        $boardPositions[37] = [48, 'texture48', 'black34.png', 'white34.png'];
3167        $boardPositions[38] = [49, 'texture49', 'black.png', 'white.png'];
3168        $boardPositions[39] = [50, 'texture50', 'black34.png', 'white34.png'];
3169        $boardPositions[40] = [51, 'texture51', 'black34.png', 'white34.png'];
3170        $boardPositions[41] = [52, 'texture52', 'black34.png', 'white34.png'];
3171        $boardPositions[42] = [53, 'texture53', 'black34.png', 'white34.png'];
3172        $boardPositions[43] = [54, 'texture54', 'black54.png', 'white54.png'];
3173        $boardPositions[44] = [23, 'texture23', 'black.png', 'whiteFlower.png'];
3174        $boardPositions[45] = [24, 'texture24', 'black24.png', 'white24.png'];
3175        $boardPositions[46] = [25, 'texture25', 'blackGhost.png', 'white.png'];
3176        $boardPositions[47] = [26, 'texture26', 'blackInvis.png', 'whiteCarnage.png'];
3177        $boardPositions[48] = [27, 'texture27', 'black27.png', 'white27.png'];
3178        $boardPositions[49] = [28, 'texture28', 'blackGiant.png', 'whiteKo.png'];
3179        $boardPositions[50] = [29, 'texture29', 'blackKo.png', 'whiteKo.png'];
3180        $boardPositions[51] = [30, 'texture55', 'blackGalaxy.png', 'whiteGalaxy.png'];
3181
3182        $boardCount = 51;
3183
3184        if ($this->Session->check('texture') || (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0')) {
3185            $splitCookie = [];
3186            if (isset($_COOKIE['texture']) && $_COOKIE['texture'] != '0') {
3187                $splitCookie = str_split($_COOKIE['texture']);
3188                $textureCookies = $_COOKIE['texture'];
3189                Auth::getUser()['texture'] = $this->Session->read('texture');
3190                $this->Session->write('texture', $_COOKIE['texture']);
3191                $this->set('textureCookies', $textureCookies);
3192            } else {
3193                if (Auth::isLoggedIn()) {
3194                    $this->Session->write('texture', Auth::getUser()['texture']);
3195                }
3196                $textureCookies = $this->Session->read('texture');
3197                $splitTextureCookies = str_split($textureCookies);
3198                $splitTextureCookiesCount = count($splitTextureCookies);
3199                for ($i = 0; $i < $splitTextureCookiesCount; $i++) {
3200                    if ($splitTextureCookies[$i] == 2) {
3201                        $enabledBoards[$i + 1] = 'checked';
3202                    } else {
3203                        $enabledBoards[$i + 1] = '';
3204                    }
3205                }
3206            }
3207
3208            $splitCookieCount = count($splitCookie);
3209            for ($i = 0; $i < $splitCookieCount; $i++) {
3210                if ($splitCookie[$i] == 2) {
3211                    $enabledBoards[$i + 1] = 'checked';
3212                } else {
3213                    $enabledBoards[$i + 1] = '';
3214                }
3215            }
3216            if (Auth::isLoggedIn()) {
3217                Auth::saveUser();
3218            }
3219        }
3220
3221        if (!$this->Session->check('texture')) {
3222            $this->Session->write('texture', '222222221111111111111111111111111111111111111111111');
3223            $enabledBoards[1] = 'checked';
3224            $enabledBoards[2] = 'checked';
3225            $enabledBoards[3] = 'checked';
3226            $enabledBoards[4] = 'checked';
3227            $enabledBoards[5] = 'checked';
3228            $enabledBoards[6] = 'checked';
3229            $enabledBoards[7] = 'checked';
3230            $enabledBoards[8] = 'checked';
3231            $enabledBoards[9] = '';
3232            $enabledBoards[10] = '';
3233            $enabledBoards[11] = '';
3234            $enabledBoards[12] = '';
3235            $enabledBoards[13] = '';
3236            $enabledBoards[14] = '';
3237            $enabledBoards[15] = '';
3238            $enabledBoards[16] = '';
3239            $enabledBoards[17] = '';
3240            $enabledBoards[18] = '';
3241            $enabledBoards[19] = '';
3242            $enabledBoards[20] = '';
3243            $enabledBoards[21] = '';
3244            $enabledBoards[22] = '';
3245            $enabledBoards[23] = '';
3246            $enabledBoards[24] = '';
3247            $enabledBoards[25] = '';
3248            $enabledBoards[26] = '';
3249            $enabledBoards[27] = '';
3250            $enabledBoards[28] = '';
3251            $enabledBoards[29] = '';
3252            $enabledBoards[30] = '';
3253            $enabledBoards[31] = '';
3254            $enabledBoards[32] = '';
3255            $enabledBoards[33] = '';
3256            $enabledBoards[34] = '';
3257            $enabledBoards[35] = '';
3258            $enabledBoards[36] = '';
3259            $enabledBoards[37] = '';
3260            $enabledBoards[38] = '';
3261            $enabledBoards[39] = '';
3262            $enabledBoards[40] = '';
3263            $enabledBoards[41] = '';
3264            $enabledBoards[42] = '';
3265            $enabledBoards[43] = '';
3266            $enabledBoards[44] = '';
3267            $enabledBoards[45] = '';
3268            $enabledBoards[46] = '';
3269            $enabledBoards[47] = '';
3270            $enabledBoards[48] = '';
3271            $enabledBoards[49] = '';
3272            $enabledBoards[50] = '';
3273            $enabledBoards[51] = '';
3274        }
3275        $achievementUpdate = [];
3276        if ($this->Session->check('initialLoading')) {
3277            $achievementUpdate1 = $this->checkLevelAchievements();
3278            $achievementUpdate2 = $this->checkProblemNumberAchievements();
3279            $achievementUpdate3 = $this->checkRatingAchievements();
3280            $achievementUpdate4 = $this->checkTimeModeAchievements();
3281            $achievementUpdate5 = $this->checkDanSolveAchievements();
3282            $achievementUpdate = array_merge(
3283                $achievementUpdate1 ?: [],
3284                $achievementUpdate2 ?: [],
3285                $achievementUpdate3 ?: [],
3286                $achievementUpdate4 ?: [],
3287                $achievementUpdate5 ?: []
3288            );
3289            $this->Session->delete('initialLoading');
3290        }
3291
3292        if (count($achievementUpdate) > 0) {
3293            $this->updateXP(Auth::getUserID(), $achievementUpdate);
3294        }
3295
3296        $nextDay = new DateTime('tomorrow');
3297        if (Auth::isLoggedIn()) {
3298            Auth::getUser()['name'] = $this->checkPicture(Auth::getUser());
3299            $this->set('user', Auth::getUser());
3300        }
3301        $this->set('mode', $mode);
3302        $this->set('nextDay', $nextDay->format('m/d/Y'));
3303        $this->set('boardNames', $boardNames);
3304        $this->set('enabledBoards', $enabledBoards);
3305        $this->set('boardPositions', $boardPositions);
3306        $this->set('highscoreLink', $highscoreLink);
3307        $this->set('achievementUpdate', $achievementUpdate);
3308        $this->set('lightDark', $lightDark);
3309        $this->set('levelBar', $levelBar);
3310        $this->set('lastProfileLeft', $lastProfileLeft);
3311        $this->set('lastProfileRight', $lastProfileRight);
3312        $this->set('resetCookies', $resetCookies);
3313        $this->set('hasFavs', $hasFavs);
3314    }
3315
3316    public function afterFilter() {}
3317}